Ad

Laravel : Injecting A Controller In A View Of Another Controller

- 1 answer

Let's say I have a NewsController::lastNews who can fetch and display some News.

I want to display this news in many others controllers (HomeController, WhateverController).

Option 1 : Fetching the data on each controller : I can fetch the data in each wanted controller (HomeController, WhateverController) directly, via a Service, or even a Trait then pass it to the view, then @include the template of my news in the template of the controller, but this looks like not very smooth

Option 2, my favorite so far : Using @inject in my templates : This is very close to the render(controller()) of Symfony but I want to know if there is any issues with this because it is not documented for using it with controllers.

@inject('news', 'App\Http\Controllers\NewsController')
<div> {{ $news->lastNews(3) }} </div>

What is the recommended way to share data + views in Laravel ? Thanks.

Ad

Answer

There is View Composer for this purpose. You can create a file that would fetch data and then specify in which views that data is available.

You would need to create ViewServiceProvider and register it in the config/app.phpproviders section.

In the ViewServiceProvider you can specify in the boot() method what view would have a specific view composer

Example of ViewServiceProvider

class ViewServiceProvider extends ServiceProvider
{
    /**
    * Register any application services.
    *
    * @return void
    */
    public function register()
    {
        //
    }

    /**
    * Bootstrap any application services.
    *
    * @return void
    */
    public function boot()
    {
        View::composer('your.view.name', YourComposerName::class);
    }
}

Example of a view composer:

use Illuminate\View\View;

class YourComposerName
{
    /**
    * Bind data to the view.
    *
    * @param  View  $view
    * @return void
    */
    public function compose(View $view)
    {

        $view->with('variable_name', ['data_that_will_be_passed_to_the_view']]);
    }
}

Link to documentation - View Composers

Ad
source: stackoverflow.com
Ad