Custom Composer class
Composer class
🧱 1. Create the Composer Class
Create a directory (optional but recommended):
mkdir -p app/View/Composers
Then create the class:
namespace App\View\Composers;
use Illuminate\View\View;use Illuminate\Support\Facades\Auth;
class UserComposer{ public function compose(View $view): void { $user = Auth::user();
$view->with('appContext', [ 'user' => $user, 'avatar' => $user?->avatar_url ?? '/images/default-avatar.png', // Add other user-wide variables here 'isAdmin' => $user?->hasRole('admin') ?? false, ]); }}
💡 This gives you a clean, testable unit of responsibility.
⚙️ 2. Register It in a Service Provider
In your AppServiceProvider
or (preferably) a custom ViewServiceProvider
:
php artisan make:provider ViewServiceProvider
Then inside boot()
:
use Illuminate\Support\Facades\View;use App\View\Composers\UserComposer;
public function boot(): void{ View::composer('*', UserComposer::class);}
And register it in bootstrap/providers.php
under bootstrap
:
return [ App\Providers\AppServiceProvider::class, App\Providers\ViewServiceProvider::class,];
🧪 3. Use It in Blade
Now in your layout or any view:
@auth <div class="flex-shrink-0"> <img class="h-10 w-15" src="{{ $appContext['avatar'] }}" alt="The user avatar"> </div>@endauth
Or:
@if ($appContext['isAdmin']) <a href="/admin">Admin Panel</a>@endif
📦 Bonus: Add More Context
You can grow UserComposer into a full UI context builder:
$view->with('appContext', [ 'user' => $user, 'avatar' => $user?->avatar_url, 'isAdmin' => $user?->hasRole('admin'), 'notifications' => $user?->unreadNotifications()->take(5)->get(),]);
This becomes the perfect place to prep things for the navbar, sidebar, user dropdown, etc.
Let me know if you want to abstract it even further into something like a UserContextBuilder
or AppContextService
, depending on how far you want to go. You’re on the right track here.