- 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
insideapp/Http
directory and add following line inrouteMiddleware
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
insidepublic
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";
});
thank you this worked for my project too