Introducing Laravel Quizzes! Play now

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:

<?php

namespace App\Providers;

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

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot(): void
    {
        View::composer('*', function ($view) {
            $view->with('logged_in_user', auth()->user());
        });
    }
}

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:

@if ($logged_in_user)
    // User is logged in
@else
    // User is a guest
@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.