Laravel 5 Pass Variables to Master Template

Published 2 years ago by adrielzxdf

Hi,

In Laravel 4, I am able to pass variables to my master template via filters.php like this:

View::composer('layout.master', function ($view) {
    view->with('variable', 'myvariable');
}

How can I achieve the same thing in Laravel 5? What would be the best practice for placing variables that can be accessed by all pages. Thanks.

Best Answer (As Selected By adrielzxdf)
JohnRivs

https://laracasts.com/series/laravel-5-fundamentals/episodes/25

Register a service provider or use AppServiceProvider.

public function boot()
{
    view()->composer('layouts.master', function($view)
    {
        $view->with('variable', 'myvariable');
    });
}

Or use a dedicated class:

// app/Providers/AppServiceProvider.php
public function boot()
{
    view()->composer('layouts.master', 'App\Http\Composers\MasterComposer');
}

// app/Http/Composers/MasterComposer.php
use Illuminate\Contracts\View\View;

class MasterComposer {

    public function compose(View $view)
    {
        $view->with('variable', 'myvariable');
    }

}
JohnRivs

https://laracasts.com/series/laravel-5-fundamentals/episodes/25

Register a service provider or use AppServiceProvider.

public function boot()
{
    view()->composer('layouts.master', function($view)
    {
        $view->with('variable', 'myvariable');
    });
}

Or use a dedicated class:

// app/Providers/AppServiceProvider.php
public function boot()
{
    view()->composer('layouts.master', 'App\Http\Composers\MasterComposer');
}

// app/Http/Composers/MasterComposer.php
use Illuminate\Contracts\View\View;

class MasterComposer {

    public function compose(View $view)
    {
        $view->with('variable', 'myvariable');
    }

}
adrielzxdf

Welp, problem solved. Thanks, I missed that one!

Please sign in or create an account to participate in this conversation.