I'm currently available for full time hire! Inquire Here

This post is more than a year old. There is a chance the content is outdated.

Snippet 3: Making the logged in user available to all views using view composers

Snippet 3: Making the logged in user available to all views using view composers


I feel like you don't hear about using view composers in Laravel anymore, like it's a dying feature that I never see in anyone's projects but mine. It's still prominent in the documentation. I just don't think many newcomers know about the feature itself.

Anyway, I don't use it too much, only when I know I have a small piece of data that I'll need in more than one view.

In all of my projects, I usually bind the currently logged-in user (or lack thereof) to a $logged_in_user variable.

First, add a ComposerServiceProvider to your App/Providers folder and register it in your app.php config file under the providers section.

Then use this code to start:

1<?php
2 
3namespace App\Providers;
4 
5use Illuminate\Support\Facades\View;
6use Illuminate\Support\ServiceProvider;
7 
8class ComposerServiceProvider extends ServiceProvider
9{
10 /**
11 * Register bindings in the container.
12 *
13 * @return void
14 */
15 public function boot(): void
16 {
17 View::composer('*', function ($view) {
18 $view->with('logged_in_user', auth()->user());
19 });
20 }
21}

This tells Laravel to bind a variable called $logged_in_user to every view. Keep in mind, this means any, including partials within master views. If you want to only bind to specific views, you can specify an array of views using dot notation.

So you can check it anywhere in any view:

1@if ($logged_in_user)
2 // User is logged in
3@else
4 // User is a guest
5@endif

Now, it might seem trivial to replace some characters with nearly the same amount, but if you needed to replace auth()->user() with something else, you would only have to do it in one place.

As another example, you can see how I share announcements across views in my boilerplate application.

Anthony Rappa

By Anthony Rappa

Hello! I'm a full stack developer from Long Island, New York. Working mainly with Laravel, Tailwind, Livewire, and Alpine.js (TALL Stack). I share everything I know about these tools and more, as well as any useful resources I find from the community. You can find me on GitHub and LinkedIn.