Search code examples
laravelauthenticationmiddleware

Authentication for different user Laravel ( Trying to get property of non-object )


Hei guys another error in authentication login, So I want to give different dashboard for different user, so example user_type = 1 it will redirect to user1/dashboard and user_type = 2 it will redirect to user2/dashboard but I got this error

Trying to get property of non-object authentication

this is my LoginController in laravel

if (Auth::attempt($credentials) && Auth::user()->user->user_type == 1) {
  // Authentication passed...
  return redirect('user1/dashboard');
  } else {
  Session::flash('login_error');
  return redirect('/login');
}

this is my middleware, I make it 2 middleware with User1Middleware and User2Middleware

if (Auth::check() && Auth::user()->users->user_type == 1)
    {
        return $next($request);
    } else {
        return redirect('/login');
    }

So Users is on my database and user_type is my table name, Can you help me guys so glad if this problem can fix very soon

From the answer I edited my code to this but still got bug it redirect to user1/dashboard not redirect to user2/dashboard even I have logic for user_type = 2

$credentials = $request->only('email', 'password','user_type');
$credentials["is_verified"] = true;
if (Auth::attempt($credentials) && Auth::user()->user_type == 1) { 
   // Authentication passed... 
return redirect('user1/dashboard'); 
} else if( Auth::attempt($credentials) && Auth::user()->user_type == 2) { 
return redirect('user2/dashboard'); 
} else { 
Session::flash('login_error'); 
return redirect('/login'); 
}

Solution

  • You don't have to do this:

    Auth::user()->user

    Because the first piece of code:

    Auth::user()

    Is the user. With this in mind, you can change your code to look like this:

    if (Auth::attempt($credentials) && Auth::user()->user_type == 1) {
      // Authentication passed...
      return redirect('user1/dashboard');
      } else {
      Session::flash('login_error');
      return redirect('/login');
    }
    
    if (Auth::check() && Auth::user()->user_type == 1)
        {
            return $next($request);
        } else {
            return redirect('/login');
        }
    

    There you go buddy!

    EDIT: Code added to question

    Your else if only checks if the user has a type, it does not have this piece of code:

    Auth::attempt($credentials)