In this article, we'll explore the process of creating custom middleware in Laravel 11. Laravel 11 introduces significant changes to middleware handling. In previous versions, you could register middleware in the Kernel.php
file. However, with Laravel 11, you must define middleware in the app.php
file.
Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.
So, let's see laravel 11 creates custom middleware, how to customize default middleware in Laravel 11, and middleware in laravel 11.
First, we'll install laravel 11 using the following command.
composer create-project --prefer-dist laravel/laravel laravel-11-example
Now, we'll create middleware using the following command.
php artisan make:middleware IsAdmin
app/Http/Middleware/IsAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class IsAdmin
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (\Auth::user()->role_id != 1) {
return response()->json('Opps! You do not have permission to access.');
}
return $next($request);
}
}
In this step, we will register our custom middleware in the app.php
file, as illustrated in the code snippet below:
bootstrap/app.php
<?php
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([
'isAdmin' => \App\Http\Middleware\IsAdmin::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
In this step, we'll create two routes and apply the "isAdmin" middleware. Let's proceed by updating the code accordingly.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['isAdmin'])->group(function () {
Route::get('/dashboard', function () {
return 'Dashboard';
});
Route::get('/users', function () {
return 'Users';
});
});
Run the laravel 11 application using the following command.
php artisan serve
You might also like: