How to get categories on all views in laravel?

Member

by addison , in category: PHP Frameworks , 5 months ago

How to get categories on all views in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 5 months ago

@addison 

To get categories on all views in Laravel, you can achieve this by using View composers.

  1. First, create a new view composer by running the following command in the terminal:
1
php artisan make:provider CategoryComposerServiceProvider


  1. 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);
    });
}


  1. Update the providers array in config/app.php file to include the newly created provider:
1
AppProvidersCategoryComposerServiceProvider::class,


  1. 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.