Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5.4 : cant access Auth::user() in the __construct method

In previous versions of Laravel, in the controllers which I needed to access logged user in all the methods I used to do something like this:

class DashboardController extends Controller
{
    private $user ;
    function __construct(Request $request)
    {
        $this->middleware('auth');
        $this->user = \Auth::user();
    }

    function func_1(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }
    function func_2(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }
    function func_3(){
      $objects = Objects::where('user_id' , $this->user->id )->get();
    }

Mostly because I don't like the default syntax \Auth::user() but after upgrading to 5.4 this doesn't work anymore and I get null from $this->user

It works fine in other methods though. Basically \Auth::user() return null in the __construct method but works fine in the other functions.

like image 914
hretic Avatar asked Jul 12 '17 10:07

hretic


People also ask

What does Auth :: check () do?

Auth::check() defers to Auth::user() . It's been that way since as long as I can remember. In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value.

What is Auth :: attempt in Laravel?

The attempt method accepts an array of key / value pairs as its first argument. The password value will be hashed. The other values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column.

Where is Auth routes in Laravel?

Route middleware can be used to allow only authenticated users to access a given route. Laravel ships with the auth middleware, which is defined in app\Http\Middleware\Authenticate. php .


1 Answers

As the doc says :

In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

So try this :

public function __construct()
{
    $this->middleware('auth');
    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();

        return $next($request);
    });
}
like image 79
Maraboc Avatar answered Nov 15 '22 18:11

Maraboc