1

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"); 
0

1 Answer 1

1

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');
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hi .. thanks for the reply. I made changes according to your code, but its still the same happening.
any more suggestions ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.