laravel Auth::user() returns null after authentication

3.1k views Asked by At

I am getting Auth::user() null in a controller. After logging in with credentials i normally get the authenticated user data but in one of my projects i am not getting the authenticated user data.

For explanation i am posting the code snippets. In NewLoginController i try to attempt the login using credentials and it is successfully logging in when i try with credentials and i can see the admin view, but when i try to go to homepage using /homepage route i get Auth::check() false and not be able to maintain the flow of the application, while in my other projects it is the same flow i have used.

Can any one guide me resolving this issue ?

class NewLoginController extends Controller
{
    public function attemptLoginApi()
    {
       
        if (Auth::attempt(['username' => request('username'), 'password' => request('password')])) {
            
            $userType = Auth::user()->user_type;
             return view('admin');
        } else {
         
            toastr()->error('Invalid Credentials', 'Error');
            return back();
        }

    }

}


class HomePageController extends Controller
{

    public function getUserHomepage()
    {
        
        if (Auth::check()) {
            
            return view('admin');
        
        } else {
         
             return view('home');

        }
        
    }
    
}

web.php

Route::get('/homepage', 'HomePageController@getUserHomepage');
Route::post('/loginApi', 'NewLoginController@attemptLoginApi')->name("loginApi"); 
1

There are 1 answers

2
Rouhollah Mazarei On

I think you have forgotten to use Auth middleware. Put your homepage route in a route group that uses Auth middleware. See the documentation .

Route::group(['middleware'=>'auth'],function () {
    Route::get('/homepage', 'HomePageController@getUserHomepage');
});