Custom redirect inside Authenticate middleware for different guards
Greetings to all members and moderators
I have defined an admin guard, and protected a group of routes using the auth:admin middleware
The problem is that when i try to access one of those protected routes, i'm getting redirected to the login route of auth:web, while i want to redirect to a route called admin.login
But i can't wrap my head around the mechanism of making it redirect to a different login route
To demonstrate my point, here's what i'm trying to do:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
if (/* visitor tried to access a web guard protected route */) {
return route('login');
}
else if (/* visitor tried to access an admin guard protected route */) {
return route('admin.login');
}
}
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Arr;
class Authenticate extends Middleware
{
protected $guards;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->guards = $guards;
return parent::handle($request, $next, ...$guards);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if (Arr::first($this->guards) === 'admin') {
return route('admin.login');
}
return route('login');
}
}
}
Isn't there anyway to handle custom redirecting in something like Handler.php as before?
I tried defining Handler.php as:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
class Handler extends ExceptionHandler
{
protected function unauthenticated($request, AuthenticationException $exception)
{
dd('hellooo');
}
}
And register it in AppServiceProvider as follows:
use App\Exceptions\Handler;
use Illuminate\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(ExceptionHandlerContract::class, Handler::class);
}
}
But it doesn't work and still gets redirected to login, never reaches the dd('hellooo');.