Table of Contents
-
Defining Middleware
-
Registering Middleware
-
Middleware Parameters
-
Terminable Middleware
1. Defining Middleware
Middleware acts as an intermediary between a request and a response. For example, if a user is not authenticated, the application may redirect them from login.php
to index.php
.
You can create middleware using the following command:
php artisan make:middleware <MiddlewareName>
Replace <MiddlewareName>
with your desired name. The created middleware will be stored in app/Http/Middleware/
.
Example:
php artisan make:middleware CheckUser
2. Registering Middleware
Before using any middleware, you must register it in your Laravel application.
Laravel provides two types of middleware:
-
Global Middleware: Runs on every HTTP request.
-
Route Middleware: Applies only to specific routes.
Global Middleware
Global middleware is listed in the $middleware
property of app/Http/Kernel.php
.
Route Middleware
Route middleware is defined in the $routeMiddleware
array of app/Http/Kernel.php
. To add custom middleware, append it to this list with a key of your choice.
Example:
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'userAuth' => \Illuminate\Routing\Middleware\UserAuthRequests::class,
];
3. Middleware Parameters
Middleware can accept parameters to handle different roles such as customer, employee, admin, or owner.
Example:
public function handle($request, Closure $next, $profile)
{
if (! $request->user()->hasProfile($profile)) {
// Redirect or handle unauthorized access
}
return $next($request);
}
To create a middleware that handles user profiles, run:
php artisan make:middleware ProfileMiddleware
The new middleware will be located in app/Http/Middleware/ProfileMiddleware.php
.
Example:
<?php
namespace App\Http\Middleware;
use Closure;
class ProfileMiddleware {
public function handle($request, Closure $next, $profile) {
echo "Role: " . $profile;
return $next($request);
}
}
4. Terminable Middleware
Terminable middleware executes tasks after a response is sent to the browser. This is achieved using the terminate
method.
Example:
<?php
namespace Illuminate\Session\Middleware;
use Closure;
class SessionBegin
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
// Perform post-response tasks
}
}