@addison
To get categories on all views in Laravel, you can achieve this by using View composers.
- First, create a new view composer by running the following command in the terminal:
1
|
php artisan make:provider CategoryComposerServiceProvider
|
- Open the newly created provider file located in app/Providers/CategoryComposerServiceProvider.php and update the boot method with the code below:
1
2
3
4
5
6
7
8
9
|
use IlluminateSupportFacadesView;
public function boot()
{
View::composer('*', function($view) {
$categories = Category::all();
$view->with('categories', $categories);
});
}
|
- Update the providers array in config/app.php file to include the newly created provider:
1
|
AppProvidersCategoryComposerServiceProvider::class,
|
- Now, you can access the $categories variable in all your views. For example, in your Blade view files, you can loop through the categories like this:
1
2
3
|
@foreach($categories as $category)
{{ $category->name }}
@endforeach
|
By following the above steps, you can easily get categories on all views in Laravel using View composers.