47
Php

Laravel 4 View Composer and Master layout

In Laravel 4 there is a very nice way to bind data automatically with a view using a View Composer. 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.

Defining a view composer according to the Laravel’s documentation is as given below

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. You may also attach a view composer to multiple views at once and also it’s possible to use a class based composer, you can read more on Laravel’s documentation.

Well, but what about layout, if we can use this view composer the same way for the master layout then it would be more helpful for us. One real use case is that, in a project using Laravel 4, I’ve a dynamic menu and I wanted the menu to be available automatically in the main layout whenever I show a page by loading a view. So, what I did is that, I’ve used view composer for my master blade layout to bind the menu with the layout, so every time I load a view, my menu becomes available to the page. Here is the code sample, I’m keeping it in filters.php file

View::composer('layouts.master', function($view){
    $menus = Page::getMenu();
    if($view->myApp->isLogedin)
    {
    	$menus[] = array('title' => 'Logout', 'link' => URL::to('logout'));
    }
    else{
    	$menus[] = array('title' => 'Login', 'link' => URL::to('logint'));
    }
    $view->with('menus', $menus);
});

This the master blade layout (Just the menu part)


And this is the file that contains the menu building loop (menu.blade.php)

@foreach( $menus as $menu )
  @if( is_array($menu['link']) )
    
  @else
      
  • {{ $menu['title'] }}
  • @endif @endforeach

    That’s all. Now every time I show a page, my menu just gets loaded automatically with the master layout in the page. In the view composer I’ve used if($view->myApp->isLogedin) to check whether the user is logged in or not and depending on that i’m showing either the login or logout link in the menu. So,the question is that, where the code if($view->myApp->isLogedin) came from, how is it related in the composer function!

    Actually, I have used the before filter of Laravel as given below

    App::before(function($request)
    {
        // $myApp Singleton object
        App::singleton('myApp', function(){
            $app = new stdClass;
            $app->title = "LaraVelFour";
            if (Auth::check()) {
                $app->user = Auth::User();
                $app->isLogedin = TRUE;
            }
            else
            {
                $app->isLogedin = FALSE;
                $app->user = FALSE:
            }
            return $app;
        });
        $app = App::make('myApp');
        View::share('myApp', $app);
    });
    

    In the before filter I’m just making a singleton object (check IoC container) and sharing it through out the application with every view, so I can use this object anytime to check the user’s login status and user data instead of using the if (Auth::check()) {...} and Auth::User() again and again, I think it’s better because Auth::User() generates a query every time I use it to access some information for the logged in user. I’m also setting the default title in this singleton IoC container and can access it using $myApp->title or $myApp->user->username from any child view. That’s all.

    Laravel 4 has added some other cool features and one of the coolest feature is Model Events. it allows a grate way to fire some events when creating, updating or deleting a model and even more. It lets us do the validation in the model directly. I think this is really a very cool feature and certainly there are a lot more to learn about Laravel 4. Just a matter of time, I’m loving it.

    Latest Blog

    0
    Php

    PHP – 8.0 Match Expression

    In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]