'laravel 9: custom login process
I created a custom guard because I want to authorize users on a custom table. So I followed this guide: tutorial
But in my custom Auth Controller if I use auth()->user(); and then redirect()->intended() I get 419 PAGE EXPIRED. If I use Auth::login($user); I can see that Auth::check() returns true but after the redirect the user is logged out.
Here is my login function in controller:
public function login(Request $request)
{
/*$this->validate($request, [
'person_username' => 'required|username',
'password' => 'required',
]);*/
$credentials = [
'person_username' => 'readmin',
'password' => 'c4ca42389a6f75849b'
];
if(auth()->guard('myg')->attempt([
'person_username' => $request->person_username,
'password' => $request->password,
])) {
//$user = auth()->user(); ->if I use this instead of the following lines I get 419 error
$user = Fiperson::where('person_username', $credentials['person_username'])->first();
Auth::login($user);
//if (Auth::check()) {dd('okkk');} //if I uncommment it I get 'okkk'
return redirect()->intended(url('/admin/dashboard'));
} else {
return redirect()->back()->withError('Credentials doesn\'t match.');
}
}
And here are my route for successful login:
Route::group(['middleware' => ['auth:myg']], function () {
Route::get('admin/dashboard', [RegateController::class, 'dashboard'])->name('admin.dashboard');
});
Solution 1:[1]
Instead auth()->user() use auth()->guard('myg')->user() as default guard is set to web.
...
if(auth()->guard('myg')->attempt([
'person_username' => $request->person_username,
'password' => $request->password,
])) {
$user = auth()->guard('myg')->user();
Auth::guard('myg')->login($user);
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | S N Sharma |
