Rafael Munoz
Rafael Munoz

Reputation: 656

Laravel: passing a variable to multiple views

I would like to make the menu dinamically, so instead showing "FILMS OF THE MONTH" it shows "FILMS OF DECEMBER" (see the image); being December the current month that update itself each month

My problem is that the menu does not belongs to an specific route/controller, therefore I can not pass the variable like I do with other routes. Example:

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

I could "solve" that problem passing the month to ALL controllers/routes, but I am repeating many times the same code.

My questions are

1- Is there any way in Laravel to pass a variable to a kind of rootstate (like in Angular) so, I keep the variable available in All routes of my application?

2- Is there any way that I could return a variable to more than one view? So I just pass the variable to all views possible like:

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

Any idea would be appreciated

The navigation is outside the scope of views UPDATE

The menu is outside the views scope

Finally I have the solution:

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

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

Upvotes: 5

Views: 6947

Answers (3)

Asim Butt
Asim Butt

Reputation: 36

Another way is to use Laravel Session. You can save variable value in session and get it anywhere.

 //To Save value in Session
   $month = 'January';
   Session::put('currentMonth', $month);

 //To Get value from Session
   if((Session::has('currentMonth'))) {
       $month_var = Session::get('currentMonth');
    }

Upvotes: 0

Robin Dirksen
Robin Dirksen

Reputation: 3422

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

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 this works!

Upvotes: 2

Amit Gupta
Amit Gupta

Reputation: 17658

You can use the share() method to share the data to multiple view. Place the following code in your boot() method of App/Providers/AppServiceProvider:

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

Docs

Upvotes: 4

Related Questions