Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel guard login

Tags:

laravel

I am a bit stuck using a custom login for my Admin users.

I pref to use another Model for my admin just to make sure everything is separated. I did see a lot examples to made a guard for the login. So watching some tutorials and read some articles I gave it a go and got stuck.

For my Admin I made a second guard.

 'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        //'hash' => false,
    ],
],

using providers:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Users\Admin::class,
    ]
]

And yes my Admin model is located as namespace App\Models\Users;

In the login controller I changed:

Auth::attempt($request->only('email', 'password'));

to:

Auth::guard('admin')->attempt($request->only('email', 'password'));

Without the guard it work/ Get a Auth with a User model. But I want the admin guard to work to get a Admin model.

Right now, nothing happend. Not a error or a Auth user.

Anyone here that see what I am doing wrong here?

P.S. I cleared config:cache etc a lot already.

UPDATE: When I changed the default Gaurd to 'admin' and login without specifying a guard. I get a Admin model back. So something goes wrong when I use the Auth::guard('admin')

like image 695
Niels Lucas Avatar asked Sep 15 '25 11:09

Niels Lucas


2 Answers

To get the user that is logged in you should also specify the guard.

So if you log-in with a guard like this:

Auth::guard('admin')->attempt($request->only('email', 'password'));

You should also retrieve the user with the guard like this:

Auth::guard('admin')->user()
like image 51
Niels Lucas Avatar answered Sep 17 '25 01:09

Niels Lucas


Have you tried using auth()->guard('admin'). I hope it helps

like image 36
gjhuerte Avatar answered Sep 17 '25 02:09

gjhuerte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!