Skip to content

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>

View composers let you attach variables to views globally or selectively.

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

Terminal window
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

MethodScopeBest For
View ComposerPer view or allCleanest solution for layout data
View::share()GlobalLightweight globals
Controller view()Per route/viewFine for unique or view-specific data