Auth()->user() or Auth::user() return wrong User Data

Viewed 365

I am facing a unique issue, There are only 3 user data in my database John, Cindy & Carla, I Login using the username john, but I get Auth data of Carla, it's supposed to be Auth data of john.

here is my Login function inside LoginController.php

public function login(Request $request) {
    $this->validateLogin($request);
    $credentials = ['user_id' => \Arr::get('user_id','', $request->input('user_id')),                  
        'password' => \Arr::get('password','', $request->input('user_password'))
    ]; 

    if(Auth::attempt($credentials)){
        return  redirect()->intended($this->redirectPath());
    }

    return back()->withInput($request->except('password'))->withErrors(['Username atau Password Wrong! ']);
}

Here is my User Model

class User extends Authenticatable {
    use Notifiable;
    use HasRoles;

    protected $table = "m_user";
    protected $primaryKey = "user_id";

    public function getAuthPassword() {
        return $this->hash_password;
    }

    protected $fillable = [
        'user_id', 'nama', 'user_password','hash_password','role', 'company','is_active','created_by','created_at','updated_by','updated_at'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

the thing is when i put dd(Auth()->user()) after the Auth::attempt() i get John User data which is correct, but if i dd(Auth()->user()) in another Controller in my Application, i get Carla Auth data. why?

FYI: Carla is the first row data in my User Table.

if(Auth::attempt($credentials)) {
   dd(auth()->user()); <---- here, i get John Auth Data
   return  redirect()->intended($this->redirectPath());
}

try to dd in another Controller. but get Carla Auth Data.

class DashboardController extends Controller {
    public function overview() {
        dd(auth()->user()); <---- i get Carla Auth Data, it's supposed to John Auth data.
    }
}

the question is that why Auth::user() or auth()->user() not return the login user's data in another Controller?

1 Answers

You could write an if statement inside if(Auth::attempt($credentials)){} to check whether it is the desirable user or not.
As a result you can debug it and make sure this problem really exists because it sounds really weird

Related