Search code examples
laravellaravel-authorization

Laravel logout, hittin gthe back button send s me back into the app, how do I prevent this


Currently I use the default laravel login/auth controllers, routes, views and no custom logic. We are building an app where if you logout and click the back button you cannot, under any circumstance "be taken back into the app, even if you have no session."

Is there a way to have the back button when clicked after you logout, not send you back into the app? Like we cant show anything once you click the back button. It should got to a laravel error screen or auto send you back to login.

All of my controllers do have $this->middleware('auth'); which should auto resend you back to the login screen.


Solution

  • If you just want to prevent the back button being used, and don't actually care that the user can hold the back button and go to earlier pages, then the following disables the back button.

    (of course you can use both disable cache and disable back button)

    Create a new 'Logged out' view

    This is optional but means you can add the javascript without worrying about affecting any other functionality.

    @extends('layouts.app',[$title='Logout | '])
    
    @section('content')
    <div class="container mx-auto">
        <div class="flex flex-wrap justify-center">
            <div class="w-full max-w-md">
    
                <h1 class="text-2xl text-gray-700 text-center">You have been successfully logged out</h1>
    
                <p class='mt-8 text-xl text-indigo-800 text-center underline'><a href="{{ route('login') }}">Login?</a></p>
    
                <script type="text/javascript">
                    history.pushState(null, null, `{{ route('logout') }}`);
                    window.addEventListener('popstate', function () {
                        history.pushState(null, null, `{{ route('logout') }}`);
                    });
                </script>
    
            </div>
        </div>
    </div>
    @endsection
    

    Create a route to display the logout page

    Route::view('/logout','auth.logout')->name('logout');
    

    Modify the login controller to go to the Logout view

    Add the following code somewhere inside App\Http\Controllers\Auth\LoginController.php

        private function loggedOut($request)
        {
            return redirect(route('logout'));
        }