Neekobus
Neekobus

Reputation: 2038

Laravel : Injecting a controller in a view of another controller

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.

Upvotes: 1

Views: 847

Answers (2)

Nikolai Kiselev
Nikolai Kiselev

Reputation: 6613

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.php providers 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

Upvotes: 1

junaid rasheed
junaid rasheed

Reputation: 161

Controllers are not meant to have static methods defined in them. Usually the best practice of defining controller methods is to have only model actions like create, update , fetch , delete etc as methods.

Your blade files should never have any php code included in them. In case you want to have shared functionality between different controllers Laravel has a global helpers.php file where you can define your static/non-static methods. You can read more about it here

Upvotes: 0

Related Questions