Middleware acts as a bridge between a request and a response. It is used to filter HTTP requests before they reach your application’s routes. Laravel’s default middleware includes tasks like checking for authenticated users or redirecting non-authenticated users.
To create custom middleware, use the following Artisan command:
php artisan make:middleware CheckRole
This command creates a middleware file in the app/Http/Middleware
directory named CheckRole.php
.
Open the CheckRole.php
file and add your custom logic:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckRole
{
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()->role !== 'admin') {
return redirect('/unauthorized'); // Redirect if the user is not an admin
}
return $next($request); // Proceed to the next middleware or route
}
}
In this example, the middleware checks if the authenticated user has the role of "admin." If not, it redirects them to an unauthorized page.
You must register the middleware before using it in your routes. Open the app/Http/Kernel.php
file and add your middleware:
protected $routeMiddleware = [
// Other middleware
'checkrole' => \App\Http\Middleware\CheckRole::class,
];
This allows you to use the checkrole
middleware in your routes.
You can apply the middleware to individual routes or groups of routes in the web.php
file:
Route::get('/admin', function () {
// Admin dashboard
})->middleware('checkrole');
You can also apply middleware to a group of routes:
Route::middleware(['checkrole'])->group(function () {
Route::get('/admin', function () {
// Admin dashboard
});
Route::get('/admin/settings', function () {
// Admin settings
});
});
Once everything is set up, test your middleware by logging in with different user roles and trying to access the protected routes.
You can pass additional parameters to middleware. For example:
Route::get('/dashboard', function () {
// Dashboard
})->middleware('checkrole:admin');
In your middleware, you can access the parameters like this:
public function handle($request, Closure $next, $role)
{
if (Auth::check() && Auth::user()->role !== $role) {
return redirect('/unauthorized');
}
return $next($request);
}
Creating and using middleware in Laravel is essential for managing request flow and applying conditional logic to routes. With custom middleware, you can build flexible and secure web applications by filtering requests efficiently.