Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Making a model available to the layout globally in Laravel

I am just starting out with Laravel and I'm putting together a quick blog site as an exercise.

I have a posts model that has posts, with content. I can list the posts, display a single post, and create a post.

I have created a categories table and model that will be related to posts (posts belong to categories). I would like to have a dropdown menu listing all the categories in my navigation layout that spans the entire app.

What's the best practice to allow the view to access that data across the entire app? It seems wrong to need to add the following to each controller method just so I can pass that data along.

$categories = Category::all(); 


like image 744
Rapture Avatar asked Feb 04 '15 21:02


2 Answers

That's what View Composers are made for.

You can register a callback function that is called everytime a certain view is rendered:

View::composer('layout', function($view){
   $view->with('categories', Category::all());

You can put this code in app/filters.php or create a new app/composers.php and include it at the end of app/start/global.php with:

require app_path().'/composers.php';
like image 60
lukasgeiter Avatar answered Nov 14 '22 22:11


Laravel 5 was released today. So this is how you would do it in the new Laravel. To do this, you want to use a View Composer [docs].

// App/Providers/ComposerServiceProvider.php
<?php namespace App\Providers;

use View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {

     * Register bindings in the container.
     * @return void
    public function boot()
        // Using class based composers...
        View::composer('posts.*', 'App\Http\ViewComposers\PostComposer');


// App/Http/Composers/PostComposer.php
<?php namespace App\Http\Composers;

use Illuminate\Contracts\View\View;

class PostComposer {

     * Bind data to the view.
     * @param  View  $view
     * @return void
    public function compose(View $view)
        $view->with('categories', Categories::all());

like image 21
searsaw Avatar answered Nov 14 '22 22:11