The default auth guard name in Laravel is 'web', but I found this confusing as it's provider is 'users'. Especially because for the admin guard the name is admin and the provider is admins (I'm using this for Nova). I'm on Laravel 6.5.2.
So I wanted to change this. In my config/auth I have:
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
and
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
and
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
In App\Models\User I have
protected $guard = 'user';
In App\Http\Controllers\Auth\LoginController I have
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:user')->except('logout');
$this->middleware('guest:admin')->except('logout');
}
Now I get the error Auth guard [web] is not defined when logging in. Is it a bad idea to change it from web to user?
I found setting up the guards quite confusing, because you can define things in:
- config/auth
- In the model (
protected $guard = 'guard_name';) - In the LoginController, RegisterController and ResetPasswordController as per the Laravel docs (protected
function guard() { return Auth::guard('guard-name');})
In this article it's described that it's possible to do what I'm trying to achieve.
3 Answers 3
I think that happens because in the default app/Providers/Route service provider.php class, there is this method that registers your roites/web.php file with the web middleware. You should change the middleware name here as well:
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
If you're using sanctum, make sure to add
'guard' => 'user',
to your sanctum.php config file.
You'll then need to run php artisan config:cache
Comments
- Change app/Providers/RouteServiceProvider.php
protected $namespaceUser = 'App\Http\Controllers\User';
public function boot()
{
...
$this->routes(function () {
Route::middleware('user')
->namespace($this->namespaceUser)
->group(base_path('routes/web.php'));
...
});
}
- Redefine guard() function on LoginController.php
protected function guard()
{
return Auth::guard('user');
}
php artisan cache:clear.php artisan config:clearandphp artisan view:clear, didn't work unfortunately.