Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel guest middleware

I have a page in my web app that should be blocked from logged in users. Similar to how a login or register page should not be accessible to already logged in users. I accomplished this by using guest middleware in controller constructor.

$this->middleware("guest")->only("page_action"); // like this

In this setup, if logged in user tries to visit that page they get redirected to home page. But I need to show a 404 not found page instead of redirecting. How can I do that?

In short, how can I make a page accessible to guest only and make it look like it does not exist to logged in users?

like image 347
Ragas Avatar asked Oct 21 '25 15:10

Ragas


2 Answers

The guest logic is inside inside App\Http\Middleware\RedirectIfAuthenticated.

if (Auth::guard($guard)->check()) {
    abort(404)
}

return $next($request);

Otherwise, you need to create a new middleware like @Atiqur suggested.

like image 112
senty Avatar answered Oct 24 '25 22:10

senty


In your method just check if the user is loggedIn, if then abort to 404 like below...

if(\Illuminate\Support\Facades\Auth::check()) {
    return abort(404);
}

#Rest of the code is for guest user.....
#
like image 43
Atiqur Avatar answered Oct 24 '25 23:10

Atiqur



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!