kendrick's avatar

Handler.php 404, instead of route fallback (Two guards)

I have two guards, the basic web for User.php and doctor for Doctor.php. Two different systems, requiring two ways for 404 redirects and authentication.

Now as I am trying to reduce points of failure , I am facing a lack of logic. I tried to implement a logic within my Handler.php file, which checks on the guard of an authenticated instance to then make a fitting 404 response. It is not working.

Handler.php

public function render($request, Exception $e)
    {
  
        if ($e instanceof ModelNotFoundException) {
           
            if(auth()->guard('web')->check()){
                return response()->view('errors.404', [], 404);
            } elseif(auth()->guard('doctor')->check()){
                return response()->view('errors.doctor.404', [], 404);
            } else{ 
                return response()->view('errors.404', [], 404);
            }
        }

        return parent::render($request, $e);

    }

As a logged in doctor, triggering a 404 pushes me into the User system, outputting the User layout. (disorientation)

If I implement fallbacks to my route group (doctor) it is only working as long as /doctor is within the url. If doctor is placed out, it gets back to the User 404.

Any suggestions or ideas to implement a middleware, which prepares for different Exceptions and then redirects based on the guard?

0 likes
2 replies
kendrick's avatar

@RIN4IK - Thanks @rin4ik

Following the logic, then I should replace api with doctor? How would I trigger the middleware for my routes?

class CheckAuth
{
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate(["api"]);

        return $next($request);
    }

    protected function authenticate(array $guards)
    {
        if (empty($guards)) {
            return $this->auth->authenticate();
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        throw new AuthenticationException('Unauthenticated.', $guards);
    }
}

Route structure

User 

   
Route::get('/home', 'UserController@index')->name('user.home')->middleware('auth');

Doctor
Route::prefix('/doctor')->group(function () {

Route::get('/home', 'DoctorController@index')->name('doctor.home')->middleware('auth:doctor');

Route::fallback(function(){
    return response()->view('errors.doctor.404', [], 404);
})->name('fallback-doctor');
});

Please or to participate in this conversation.