How to add middleware to restrict user access without login in Laravel 11?

I am developing a project in which I have to make sure that the user can access the page only if he is logged in, otherwise he should remain at the login page. For which I am going to use middleware. First of all, I will create a middleware and name it “isLogin“.

command : php artisan make:middleware isLogin

After running this command, I will check whether the user-id is set in the session or not, which is set when the user logs in.

1. Set user-id in session on login

public function AdminLoginProccess(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $adminUser = AdminAdmin::where('email', $credentials['email'])->first();

        if ($adminUser) {
            $password = $request->request->get('password');
            if ($password) {
                $request->session()->put('isAdmin', $adminUser->id);
                $request->session()->put('adminName', $adminUser->name);

                return redirect()->route('admin.dashboard');
            } else {
                return back()->with('error', 'Invalid Password.')->withInput();
            }
        } else {
            return back()->with('error', 'Invalid Email.')->withInput();
        }
    }

2. isLogin Middleware

<?php

namespace App\Http\Middleware\Admin;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Login
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if($request->session()->has('isAdmin')){
            return $next($request);
        }
        return redirect()->route('admin.login');
    }
}

After creating the middleware, it also has to be registered. So in Laravel 11, this has to be done in the app.php file inside the bootstrap folder.

3. Registering middleware in App.php

<?php

use App\Http\Middleware\Admin\Login;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'isAdminLogin' => Login::class
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Previous versions of Laravel used kernel.php file to register middleware.

After registering the middleware, we can use it with routes in our wep.php, which will check all the routes whether the user-id is set in the session or not.

4. Use in routes

Route::get('/dashboard', [Admin::class, 'adminDashboard'])->name('dashboard')->middleware('isAdminLogin');

These are the steps to restrict the users to access features only after login.

Scroll to top