LARAVEL

Laravel Middleware & Authentication

February 6, 2024 14 min read

Introduction

Middleware provides a way to filter HTTP requests entering your application. Laravel's authentication system is built on middleware, allowing you to easily protect routes and implement custom authorization logic.

Creating Middleware

Create middleware using the Artisan CLI:

php artisan make:middleware CheckAge
// app/Http/Middleware/CheckAge.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAge
{
    public function handle(Request $request, Closure $next, $age = 18)
    {
        if ($request->age < $age) {
            return redirect('/home');
        }
        
        return $next($request);
    }
}

Applying Middleware

Register middleware in the kernel and apply to routes:

// routes/web.php
Route::get('/admin', [AdminController::class, 'index'])
    ->middleware(['auth', 'admin']);

Route::middleware(['verified'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});
// Controller constructor
public function __construct()
{
    $this->middleware('auth');
    $this->middleware('log')->only(['store', 'update']);
}

Authentication Guards

Configure multiple authentication guards in config/auth.php:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
    
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],
// Using specific guards
Auth::guard('admin')->login($admin);
Auth::guard('api')->user();

Custom Auth Providers

Create custom authentication providers:

// app/Providers/AuthServiceProvider.php

public function boot()
{
    Auth::provider('ldap', function ($app, array $config) {
        return new LdapUserProvider($app->make(LdapConnection::class));
    });
}

Summary

Laravel's middleware and authentication systems provide powerful tools for securing your application. Use middleware to filter requests and guards to manage authentication across different user types.

For more Laravel tutorials, check out our guides on Security Best Practices and OAuth2 with Passport.