Laravel 5.4 access auth in constructor using middleware

David Carr

Laravel Framework

There are times it’s useful to be able to access the auth system in a construct method. You can’t use Auth::user or auth()->user() as its not yet been made available.

This is where middleware comes in, using middleware the auth can be used once it becomes available. In the below example  when the middleware is called the auth()->user() is added to the property $this->user

The return $next($request) is required to carry on with the normal flow of the request.

$this->middleware(function ($request, $next) {
    $this->user = auth()->user();

    return $next($request);
});

From here $this->user can be used to access the user object.

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.