I found a solution, but open if someone has an easier one.
- Create a new "Authentication guard" (name
guest) with it's own "User Provider.
//config/auth.php
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'guest' => [
'driver' => 'session',
'provider' => 'guests',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'guests' => [
'driver' => 'guest',
'model' => App\Models\Guest::class,
],
],
- In the provider, override
updateRememberToken() to avoid saving something in the database when logout
class GuestProvider extends EloquentUserProvider {
public function updateRememberToken(UserContract $user, $token)
{
}
}
- Create a middleware before the middleware
\Illuminate\Auth\Middleware\Authorize::class to authenticate the guest and change the default guard on the fly.
public function handle($request, Closure $next)
{
if (!Auth::check()) {
Auth::guard('guest')->login(new Guest);
config(['auth.defaults.guard' => 'guest']);
}
return $next($request);
}
- Let Laravel manage the permission as if was standard
- "Logout" the guest in the following middleware, and set the default guard back to the default one.
public function handle($request, Closure $next)
{
if(Auth::id() == null){
Auth::guard('guest')->logout();
config(['auth.defaults.guard' => 'web']);
}
return $next($request);
}
It works, but maybe someone has an easier solution ?