Blade view composers in Laravel allow you to share data with multiple views without duplicating code. They are similar to middleware, but designed specifically for views.
To create and use Blade view composers in Laravel, follow these steps:
Create a new composer class: Run the following command to generate a new class file that extends the ViewComposer
class.
php artisan make:composer {ComposerName}
Replace {ComposerName}
with the desired name for your composer.
Open the generated composer class and modify the composers
method. This method defines the views that the composer will be bound to, and it should return an array of view and callback pairs. The view specifies the view name or an array of view names, and the callback is a closure that receives an instance of the View
class and allows you to bind data to the view.
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ComposerName
{
public function composers(): array
{
return [
'view.name' => function (View $view) {
// Bind data to the view
$view->with('key', 'value');
},
];
}
}
Replace 'view.name'
with the desired view name. You can define multiple views and their respective data bindings in the returned array.
Register the composer: Open the AppServiceProvider
class located in app/Providers
, and import your composer class at the top of the file.
use App\Http\View\Composers\ComposerName;
Then, locate the boot
method and add the following code to call the composers
method and register your composer.
public function boot()
{
// ...
View::composer((new ComposerName)->composers());
}
Use the shared data in your views: In your Blade views, you can access the data that you bound in the composer using the assigned key. For example, in a view called example.blade.php
, you can access the data using {{ $key }}
.
And that's it! Your Blade view composer is now registered and ready to share data with the specified views.