agyanadda@gmail.com

Laravel Middleware and Authentication

Forms, Security and APIs 1 min read Updated Dec 2, 2026 Topic 12 of 13

Middleware is code that runs before (or after) a request reaches your controller — like a security guard at the door. Laravel uses middleware for login checks, CSRF protection and more.

Add login and registration

Laravel starter kits (such as Breeze) generate login, registration, password reset and profile pages for you. With Breeze:

  1. composer require laravel/breeze --dev
  2. php artisan breeze:install
  3. php artisan migrate and npm install && npm run build

Protect routes

Add the auth middleware: visitors who are not logged in are redirected to the login page.

The logged-in user

  • auth()->user() or $request->user() — the current user
  • auth()->check() — is someone logged in?
  • @auth ... @endauth and @guest ... @endguest in Blade

Your own middleware

php artisan make:middleware EnsureUserIsAdmin creates a class with a handle() method. In Laravel 11 and later, register aliases in bootstrap/app.php.

Passwords are always stored hashed (bcrypt by default) — never as plain text.

Example

Example — Protect routes and check for admins PHP
<?php
// routes/web.php
Route::middleware('auth')->group(function () {
    Route::get('/dashboard', fn () => view('dashboard'));
    Route::resource('posts', PostController::class);
});

// app/Http/Middleware/EnsureUserIsAdmin.php
public function handle(Request $request, Closure $next): Response
{
    if (! $request->user()?->is_admin) {
        abort(403, 'Admins only');
    }

    return $next($request);
}

// bootstrap/app.php (Laravel 11+)
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias(['admin' => EnsureUserIsAdmin::class]);
})

A guest who opens /dashboard is sent to /login. Routes with ->middleware('admin') show a 403 "Admins only" page to users who are not admins.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does the auth middleware do for a guest?

Exercise 2 True / False

Laravel stores user passwords as plain text in the database.

Exercise 3 Fill in the Blank

Inside handle(), call $___($request) to let the request continue.

Frequently Asked Questions

Breeze with Blade is the simplest: plain Blade views and a little Tailwind CSS, easy to read and change. Check the Laravel docs for the current starter kits, as newer releases also offer React, Vue and Livewire kits.