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

searchbar's avatar

Middleware to check if session exists

Basically i am using a completely custom authentication in Laravel 5.3. I have everything done except for figuring out how i can assign a middleware to specific routes that will simply do a check to see if Session:get('user') is set.

If its set, then they should be allowed to get access to that route.

I am relatively new to Laravel, so do excuse me if its an easy fix. I've tried many workarounds, but have not been successful.

Thanks in advance!

0 likes
7 replies
CodeNathan's avatar
Level 19

Sure you can do a check if there is no value ,

create a custom middleware as such :-

<?php

namespace App\Http\Middleware;

use Closure;

class CheckUserSession
{

    public function handle($request, Closure $next)
    {
        if (!$request->session()->exists('user')) {
            // user value cannot be found in session
            return redirect('/');
        }

        return $next($request);
    }

}

then add this to Kernel.php located inside App\Http. This should go in the $routeMiddleware property array.

       'usersession' => \App\Http\Middleware\CheckUserSession::class

finally apply it to your routes for example

    Route::group(['middleware' => 'usersession'], function () {
        Route::get('/', function ()    {
            // Uses User Session Middleware
        });
    });

I suggest go through jeffrey's series on laravel it really will help you, thats how i learnt all of this!

6 likes
mp3man's avatar

I love Laravel! That's was just what I was looking for! But in my case, I have a small change, on web.php I've done simplier as you (5.5 version):

Route::get('/admin/main', 'WebAdminController@main')
    ->middleware('adminAuth');
Kamrul_H's avatar

@CODENATHAN - I creareated custom middleware like this one, but it made a fatal error- (1/1) FatalThrowableError Class 'App\Http\Controllers\Route' not found

How can i fixed it? (laravel 5.4)

Vilfago's avatar

Create a new thread with your code.

But it seems you have a typo

Kamrul_H's avatar

@VILFAGO - Actually, I want to redirect to a custom page if session is not set. But I'm not able to edit what make a redirect to the build in login page

Please or to participate in this conversation.