Skip to content
Advertisement

Laravel Auth::user() always null

I have created this login function it returns login success when entering the correct user name and password

public function login(Request $request){

        if(Auth::user()){
            return response()->json(['success'=>'already lodged.',200]);
        }else{
            $this->validate($request,[
                'email' => 'required|email',
                'password' => 'required|alphaNum|min:6'
            ]);
            $user_data = array(
                'email' => $request->get('email'),
                'password' => $request->get('password')
            );

            if(Auth::attempt($user_data)){
                return response()->json(['success'=>'login success.',401]);
            }else{
                return response()->json(['error'=>'Unauthenticated.',401]);
            }
        }

    }

I have to define route like this in route/api.php

Route::group(['prefix' => 'web'],function (){
    Route::get('/reg',function (){
        return view('pages.temp.register');
    });
    Route::get('/login',function (){
        return view('pages.temp.login');
    })->name('login');
});

Route::get('/userdashboard', 'UserController@index')->middleware('auth');
Route::get('/user/{id}', 'UserController@show')->middleware('auth');

but when I call Auth::user() in another controller or another view it returns null what is wrong with it

Advertisement

Answer

I have fixed this error. I have created an authentication route in route/api.php. API route not supported to the session so it does not store user data in the session because that Auth::user() always returns null. please view this answer https://stackoverflow.com/a/44863089/13729121

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement