Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Passing default variables to view

Tags:

php

laravel

In Laravel, we all pass data to our view in pretty much the same way

$data = array(
    'thundercats' => 'Hoooooooooooh!'
);
return View::make('myawesomeview', $data);

But is there some way to add default variables to the view without having to declare it over and over in $data? This would be very helpful for repeating variables such as usernames, PHP logic, and even CSS styles if the site demands it.

like image 490
enchance Avatar asked Jul 15 '13 00:07

enchance


1 Answers

Use View Composers

View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".

Defining A View Composer :

View::composer('profile', function($view)
{
    $view->with('count', User::count());
});

Now each time the profile view is created, the count data will be bound to the view. In your case, it could be for id :

    View::composer('myawesomeview', function($view)
    {
        $view->with('id', 'someId');
    });

So the $id will be available to your myawesomeview view each time you create the view using :

View::make('myawesomeview', $data);

You may also attach a view composer to multiple views at once:

View::composer(array('profile','dashboard'), function($view)
{
    $view->with('count', User::count());
});

If you would rather use a class based composer, which will provide the benefits of being resolved through the application IoC Container, you may do so:

View::composer('profile', 'ProfileComposer');

A view composer class should be defined like so:

class ProfileComposer {
    public function compose($view)
    {
        $view->with('count', User::count());
    }
}

Documentation and you can read this article too.

like image 113
The Alpha Avatar answered Sep 20 '22 23:09

The Alpha