How to Pass Data to All Views in Laravel 9
Sometimes you need to share data with all views in Laravel 9, for example, if we have a categories table and we want to display it on multiple pages, here comes the View facade's share method.
Update AppServiceProvider
In the AppServiceProvider boot method, we call the View facade's share method, we give the key and value which is the categories retrieved from the database, now you can use the key to display categories in all your views.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
use App\Models\Category;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
View::share('categories',Category::has('posts')->get());
}
}