I want a different Model the be able to login too.
The name of the Model is Client.
So this is added this to auth.php
config:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Models\Client::class,
],
],
And expected that this should work:
Auth::guard('client')->loginUsingId($client->id, true);
But this doesn't show any Authenticated Client:
return Auth::guard('client')->user();
What am I missing?
Routes are like this:
Route::group(['middleware' => ['auth:client']], function () {
Route::get('my-orders', [OrderController::class, 'index']); //goes to login route });
This is the login code:
Auth::guard('client')->loginUsingId($client->id, true);
ray(['Auth' => Auth::guard('client')->user()]); // Shows correct Auth
return redirect()->to("/{$locale}/my-orders"); // Re-redirects to Login route
If you're using auth in another model you have to use Illuminate\Contracts\Auth\Authenticatable
interface and Illuminate\Auth\Authenticatable
trait
Example
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
class Client extends Model implements AuthenticatableContract
{
use Authenticatable;
}
then
php artisan config:cache
after that, these will work
Auth::guard('client')->loginUsingId($client->id, true)
Auth::guard('client')->user()
Make sure you've required columns
username
andpassword
andremember_token
Edit 01
In redirectIfAuthenticated
(located in app/Http/Middleware/RedirectIfAuthenticated.php
)
add this
public function handle($request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
switch ($guard) {
case 'client':
return redirect(route('client.dashboard'));
default:
return redirect(RouteServiceProvider::HOME);
}
}
}
return $next($request);
}
Updating middleware to be aware of the new guard.