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();
Thanks!
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';
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With