Kylie
Kylie

Reputation: 11749

Auth not persisting in Laravel 5.2

I have my auth doing this on login.

if (Auth::attempt($userdata)) {
    dd(Auth::user()); //this shows the user just fine, 
                      //which proves that the auth driver is working.
    return redirect()->intended('dashboard');
} 

However, after redirecting to the dashboard. It appears the auth isn't persisted. If I do dd(Auth::user()) or even just Auth::check() it returns null.

Here's the route:

Route::group(['middleware' => ['web']], function () {
     Route::get('test',function(){
       dd(Auth::user()); //returns null
        echo Auth::user()->name; // returns Trying to get property of non-object
     });
});

What am I doing wrong?

The weird thing about this is that last night it was working. It kinda just magically stopped working.

Upvotes: 2

Views: 2301

Answers (2)

Kylie
Kylie

Reputation: 11749

The solution to this is not an obvious one, specially coming from older versions of laravel.
Thanks to this link. Auth Session killed in Laravel 5.2
I was able to solve it, so I'll post the answer to help others who encounter the same issue.

Originally I just had this in my routes.

Route::post('app/login', 'Auth\AuthController@doLogin');

Route::group(['middleware' => ['web','auth']], function () {
     Route::get('test',function(){
        dd(Auth::user());// was always returning null
     });
});

But, to get the login to persist, I had to do this

Route::group(['middleware' =>[ 'web']], function () {
   Route::post('app/login', 'Auth\AuthController@doLogin');
});

Route::group(['middleware' => ['web','auth']], function () {
     Route::get('test',function(){
        echo Auth::user()->name;
     });
});

Apparently any route thats going to call or register a session needs to employ the 'web' middleware.

Upvotes: 1

Novica Vukobratovic
Novica Vukobratovic

Reputation: 93

Just add the "auth" middleware to your "test" route and try accessing it while logged in. It shouldn't give you any errors that way. If you try to access it without logging in, it should redirect you to whatever route is defined in the "auth" middleware.

By using "auth" middleware, you are basically ensuring that Auth::user() will always return a proper User instance.

Now, if this works then you can be sure that Laravel Auth is indeed persisting the user and the issue is somewhere else in your code.

I haven't noticed any issues with the Auth class in Laravel.

Upvotes: 0

Related Questions