AlyaKra
AlyaKra

Reputation: 566

Laravel: Trying to get property 'id' of non-object for Auth::User()->id;

I have the following login controller :

public function userLogin(Request $request) {

    $rules = [
        'email' => 'required|exists:users',
        'password'  => 'required'
    ];
    $request->validate($rules);
    $data = [
        'email' => $request->get('email'),
        'password'  =>  $request->get('password'),
    ];

    if(Auth::attempt($data))
    {
        $user = Auth::User();
        $userid = Auth::User()->id;
        
        return response()->json([
            'user'  =>  $user, 
            'token' =>  $user->createToken('yourAppName')->accessToken ,

             $userid
        ]);

    }
    else
    {
        return response()->json('Unauthorized', 401);
    }

}

My web.php ( Token is generated with Laravel Passport )

Route::get('/customize/{id}', function ($id) {
 
    if (
        User::where('id', Auth::User()->id)->whereHas('profile', function ($query) use ($id) {
            return $query->where('id', $id);
        })
        ->exists()
    )  {
        return view( 'welcome' );
      }      
      return "no";
});

For some reason, when testing my logincontroller with POSTMAN, I actually receive a value for Auth::User()->id . But in web.php I receive Trying to get property 'id' of non-object. Any idea ?

Upvotes: 0

Views: 515

Answers (2)

milad hedayatpoor
milad hedayatpoor

Reputation: 636

here is a solution

you can find that user in db with email and password you have and get its id

and then use LoginUsingId($id) to login your user

Upvotes: 1

Mahdi Jedari
Mahdi Jedari

Reputation: 758

Find out why you are not considered as an authenticated user. I can guess you send Authentication token in your request headers when you use Postman. that this is not possible when you hit the address in the browser directly.

Upvotes: 0

Related Questions