Laravel 5.4 access auth in constructor using middleware

David Carr

1 min read - 28th May, 2017

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.

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.