Laravel: passing a variable to multiple points of view

I would like to make the menu dynamically, so instead of showing "MOVIES OF THE MONTH", it shows "MOVIES OF DECEMBER" (see image); December of the current month, which is updated every month

My problem is that the menu does not belong to a specific route / controller, so I cannot pass a variable, as I do with other routes. Example:

    $month = Carbon::now()->format('F');
    return view('partials._nav')
            ->withMonth($month);

I could "solve" this problem by passing the month to all the ALL controllers / routes, but I repeat the same code many times.

My questions

1 Is there a way in Laravel to pass the variable to some kind of rootstate (e.g. in Angular), so I keep the variable available in all routes of my application?

2 Is there a way to return a variable in multiple views? Therefore, I simply pass the variable in all possible forms, for example:

return view('films.all', 'films.show', 'films.index', 'actors.show', 'actors.index')
                ->withMonth($month);

Any idea would be appreciated.

Navigation out of sight UPDATE

Menu is out of scope

Finally, I have a solution:

public function boot()
{
    View::composer('*', function ($view) {
        $month = Carbon::now()->format('F');

        $view->withMonth($month);
    });
}
+4
source share
2 answers

You can use AppServiceProvider, you pass the variable through a layout that you extend.

Your code will be:

public function boot()
{
    View::composer('*', function ($view) {
        $var = 'value';

        $view->with('var', $var);
    });

    View::composer('*', function ($view) {
        $month = Carbon::now()->format('F');

        $view->withMonth($month);
    });
}

And you need to use the following class: use Illuminate\Support\Facades\View;

Hope it works!

+2
source

You can use the method share()to exchange data with several views. Put the following code in your boot()method App/Providers/AppServiceProvider:

public function boot()
{
    view()->share('key', 'value');
} 

Docs

+2
source

Source: https://habr.com/ru/post/1664155/


All Articles