I have been struggling with creating a second authentication alongside with the out-of-the-box authentication in Laravel.
I used the make:auth command from artisan and used my custom model as provider and also created a guard for my custom model.
My issue is that the user does not get authenticated after a successful login.
So in other words, when I try to retrieve the user with: Auth::user() or Auth::guard('employee')->user() it just gives me null and I cannot understand why this is happening.
The thing is that I get redirected correctly but I don't know if its the session or anything else that is not working? Correct me if I am wrong
Edit:
My employee model:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Angestellter extends Authenticatable
{
use HasFactory;
public $timestamps = false;
protected $table = 'angestellter';
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'friseurkuerzel',
'vorname',
'nachname',
'email',
'password',
'ist_admin',
'erstelldatum',
'friseursalon_id',
];
}
My guard config from /config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'employee' => [
'driver' => 'session',
'provider' => 'employees',
]
],
My AdminLoginController where I log in my user:
$this->validate($request, $rules);
$remember = $request->get('remember');
if (Auth::guard('employee')->attempt([
'email' => $request->get('email'),
'password' => $request->get('password'),
], $remember)) {
//Authentication passed...
Auth::guard('employee')->login(Auth::guard('employee')->user());
return redirect()->to(route('admin.home'))->send();
}
After the attempt() method succeeds, I am able to dd() my Auth user with: Auth::guard('employee')->user()
But after the redirect, the Auth user is null wherever I dd() him.
I have just for the sake of testing tried to access him on my admin.home view via dd() after a successful redirect.
AuthAuth::guard('employee')->login(Auth::guard('employee')->user());...Auth::guard('employee')->user()is the authenticated user (they are already logged in by theattemptmethod call) and you should not be callingsendon the response (that gets called by the bootstrap script that started the application after the response makes its way out of the Kernel)Auth::guard('employee')->user()it is the Auth User. I am using the login() function to set the Auth User in the session but as I said, after the redirect I am getting auth user = null. Btw I am calling thesendbecause else I won't be redirected to my admin.home view. Any ideas?send... that gets called after the response has made its way out of the kernel ... you DO NOT call that method yourself you just return your responses