Compose layout values
Providing Layout Variables in Laravel (e.g., $userAvatar
for app.blade.php
)
In Laravel applications, layouts like resources/views/layouts/app.blade.php
are commonly used as the base template for all views. If your layout requires dynamic data (like a userβs avatar), you need to pass that data globally β not just from individual controllers.
This guide shows three common ways to provide layout-level variables in Laravel, using $userAvatar
as an example.
π’ Example Use Case
In your Blade layout file (app.blade.php
):
<div class="flex-shrink-0"> <img class="h-10 w-15" src="{{ $userAvatar }}" alt="The user avatar"></div>
β Option 1: Use a View Composer (Recommended)
View composers let you attach variables to views globally or selectively.
- Add Logic in
AppServiceProvider
or a Custom Provider
Open app/Providers/AppServiceProvider.php
and modify the boot() method:
use Illuminate\Support\Facades\View;use Illuminate\Support\Facades\Auth;
public function boot(){ View::composer('*', function ($view) { $user = Auth::user(); $view->with('userAvatar', $user?->avatar_url ?? '/images/default-avatar.png'); });}
- targets all views.
Auth::user()?->avatar_url
uses null-safe access.- Replace
/images/default-avatar.png
with your actual fallback path.
- Optional: Use a Specific View or Layout
If you only want to target views that use a specific layout:
View::composer('layouts.app', function ($view) { // same logic here});
β Option 3: Pass Manually from Each Controller
You can pass variables to views directly in controllers:
`return view('dashboard', [ 'userAvatar' => Auth::user()?->avatar_url ?? '/images/default-avatar.png',]);
β Not ideal for layout variables, because you must do this for every controller and route.
π‘οΈ Bonus: Add a Fallback in the Blade Template
For safety, you can also handle the fallback directly in the Blade file:
<img class="h-10 w-15" src="{{ $userAvatar ?? '/images/default-avatar.png' }}" alt="The user avatar">
But this is optional if your logic already handles the fallback.
π¦ Alternative: Custom ViewServiceProvider
If you prefer to keep view-related bindings separate, create a new service provider:
php artisan make:provider ViewServiceProvider
In the new provider:
public function boot(){ View::composer('*', function ($view) { $view->with('userAvatar', Auth::user()?->avatar_url ?? '/images/default-avatar.png'); });}
Register it in config/app.php
:
App\Providers\ViewServiceProvider::class,
β Summary
Method | Scope | Best For |
---|---|---|
View Composer | Per view or all | Cleanest solution for layout data |
View::share() | Global | Lightweight globals |
Controller view() | Per route/view | Fine for unique or view-specific data |