Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ErikRobles's avatar

Prevent Browser back button after logout. Throwing Error

Hello. I am working with Laravel 8 and wanted a way to prevent users from hitting the back button after logout and thus re-entering the dashboard. I am using a middleware called preventBackHistory and it is working great. However, because I am wipping the session, the role no longer exists and I am ending up on a page that returns null. What I am trying to do is if there is no role or I get some kind of null value, that I am redirected to my view.errors.404 page. So far, I am not clear on what needs to be done to make this happen. So, in my Home controller, I am running the following check in my index method:

public function index() {
        dd(Auth::user());
        $role = Auth::user()->role;
        if($role == 1) {
            return view('admin.index');
        } elseif($role == 0) {
            return view('user.index');
        } else { 
            return view('errors.404');
        }
    }

my redirects route calling my index method is as follows:

Route::get('redirects', [HomeController::class, 'index']);

and when I hit the back button, my browser is taking me to http://127.0.0.1:8000/redirects and when doing a dd on the value of Augh::user(); I obviously get null.

Can anyone help me come up with a better solution to handle what I am trying to do? I would certainly appreicate it. Thank you in advance.

0 likes
6 replies
martinbean's avatar

@erikrobles You should not be trying to disable the back button. It’s native browser UI. It doesn’t belong to you or your web app.

Use appropriate cache headers to stop your dashboard from being cached. Not that hitting the back button would re-authenticate the user any way. If they’ve logged out, then any action they take would just result in an unauthorised error.

ErikRobles's avatar

@martinbean Agreed. Any clues or links you can point me too that could throw a better error for the user if they try to access an unauthorized page?

Snapey's avatar
Snapey
Best Answer
Level 122

why is your route not protected with auth middleware?

1 like
ErikRobles's avatar

@Snapey Still learning. Let me do some research into this and hopefully I can come back better informed. Thanks for your advice.

ErikRobles's avatar

@Snapey I wrapped my redirects in the auth middleware and now it redirects me exactly where I want it to. Thank you @snapey

jlrdw's avatar

Normally if you set up a redirect to a friendly page perhaps saying you are now logged out will do the trick.

1 like

Please or to participate in this conversation.