Skip to content

Instantly share code, notes, and snippets.

@edomaru
Last active February 3, 2023 08:47
Show Gist options
  • Save edomaru/061caa8dd596edf928cc9153fbb8ef62 to your computer and use it in GitHub Desktop.
Save edomaru/061caa8dd596edf928cc9153fbb8ef62 to your computer and use it in GitHub Desktop.
Laravel AJAX Session Expired Checker

AJAX check session expired

  • Create a middleware

php artisan make:middleware AjaxSessionExpiredMiddleware

  • Open the AjaxSessionExpiredMiddleware and add following code:
<?php

namespace App\Http\Middleware;

use Closure;

class AjaxSessionExpiredMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->ajax() && \Auth::guest()) {
            return response()->json(['message' => 'Session expired'], 403);
        }

        return $next($request);
    }
}
  • Open Kernel.php inside app/Http directory and add following line in routeMiddleware property:

'ajax-session-expired' => \App\Http\Middleware\AjaxSessionExpiredMiddleware::class,

  • Open TodoListsController and add following code:
class TodoListsController extends Controller
{
    public function __construct()
    {
        // check if session expired for ajax request
        $this->middleware('ajax-session-expired');

        // check if user is autenticated for non-ajax request
        $this->middleware('auth');
    }

    // ..
}
  • Do the same thing for TasksController file

  • Open app.js inside public directory and add following code:

$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    alert("Session expired. You'll be take to the login page");
    location.href = "/login"; 
});
@tom-njoroge
Copy link

Thanks @edomaru, this has worked for my project.

@tornadofay
Copy link

thank you this worked for my project too

@isairuiz
Copy link

Hi, this works but when occurs another error like Internal Server Error (500) from any method on the controller the alert shows, you know how to avoid this? Thanks.

@tursunbaevz
Copy link

where is TodoListsController ? or i should create it manually ?

@htetaung-frobom
Copy link

@edomaru, the page is not return, but it shown in console.
Thanks in advance.

@rajashekar-v
Copy link

Thanks bro you have saved my day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment