Writing

Laravel View Composers: Sharing Data Across Blade Views Efficiently

Aug 2023 · 3 min read


Some data belongs to the layout, not to one page: the navigation categories, the cart count, the logged in user's name. Passing that data from every controller action is boring and easy to forget. View Composers solve this by attaching data to a view every time it renders, no matter which controller sent it.

A quick closure composer

app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        View::composer('layouts.app', function ($view) {
            $view->with('cartCount', auth()->user()?->cartItems()->count() ?? 0);
        });
    }
}

Now layouts.app always has a $cartCount variable, and no controller had to pass it.

A class composer for bigger data

app/Http/View/Composers/NavigationComposer.php

<?php

namespace App\Http\View\Composers;

use App\Models\Category;
use Illuminate\View\View;

class NavigationComposer
{
    public function compose(View $view): void
    {
        $view->with('categories', Category::orderBy('name')->get());
    }
}

app/Providers/AppServiceProvider.php (boot method)

use App\Http\View\Composers\NavigationComposer;
use Illuminate\Support\Facades\View;

public function boot(): void
{
    View::composer('layouts.*', NavigationComposer::class);
}

The wildcard layouts.* means every view inside the layouts folder receives the categories. In Blade you just loop over them:

resources/views/layouts/app.blade.php

<nav>
    @foreach ($categories as $category)
        <a href="{{ url('/categories/' . $category->slug) }}">
            {{ $category->name }}
        </a>
    @endforeach
</nav>

Why it helps

Controllers stop repeating the same queries, and the layout data is always there even for pages you forgot about. If the query is heavy, wrap it in Cache::remember inside the composer so it does not run on every request. Use composers for layout level data; keep page specific data in the controller or a ViewModel.