Learn how to create custom middleware in Laravel 11 with this comprehensive step-by-step guide. This tutorial covers the installation of Laravel 11, the creation of middleware, and applying it to routes, providing you with the knowledge to effectively manage middleware in your Laravel applications.
Laravel 11 introduces significant changes to middleware handling compared to previous versions. Previously, middleware was registered in the Kernel.php file, but now, Laravel 11 requires you to define middleware in the app.php file. This update streamlines middleware management and enhances flexibility in handling HTTP requests.
Middleware in Laravel provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. With custom middleware, you can implement various functionalities such as authentication, logging, and more.
In this guide, we’ll explore how to create custom middleware in Laravel 11, customize default middleware, and understand its application in Laravel 11.
Step 1: Install Laravel 11
To start, we need to install Laravel 11. Open your terminal and run the following Composer command:
composer create-project --prefer-dist laravel/laravel laravel-11-example
This command sets up a fresh Laravel 11 project in a directory named “laravel-11-example”. You can now proceed to add your custom middleware.
Step 2: Create Middleware in Laravel 11
Once Laravel is installed, the next step is to create middleware. Use the following Artisan command to generate a new middleware class:
php artisan make:middleware IsAdmin
This command creates a new middleware file called IsAdmin.php under the app/Http/Middleware directory. You can now define your custom logic in this file.
Step 3: Edit Middleware (app/Http/Middleware/IsAdmin.php)
Open the newly created IsAdmin.php file and add the following code to handle requests based on user roles:
namespace App\Http\Middleware;
use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response;
class IsAdmin {
public function handle(Request $request, Closure $next): Response {
if (\Auth::user()->role_id != 1) {
return response()->json('Oops! You do not have permission to access.');
}
return $next($request);
}
}
This middleware checks if the authenticated user has the role of an admin. If not, it returns a JSON response denying access.
Step 4: Register Custom Middleware in Laravel 11
To use the custom middleware, you need to register it in the bootstrap/app.php file. Here’s how you do it:
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();
By adding this code, you ensure that the isAdmin middleware is registered and available for use in your application.
Step 5: Apply Middleware to Routes
With the middleware registered, you can now apply it to specific routes in routes/web.php. Here’s how:
use Illuminate\Support\Facades\Route;
Route::middleware(['isAdmin'])->group(function () {
Route::get('/dashboard', function () { return 'Dashboard';
});
Route::get('/users', function () {
return 'Users';
});
});
This setup restricts access to the /dashboard and /users routes to users who pass the isAdmin middleware check.
Step 6: Run the Laravel 11 Application
Finally, to test the middleware, start the Laravel application using the following command:
php artisan serve
Access your application in a web browser to see the middleware in action. You should see the restricted routes only accessible to users with the correct role.
For more detail you can write Laravel Documentation
Summary
Creating custom middleware in Laravel 11 is a straightforward process that provides powerful control over how your application handles HTTP requests. By following these steps, you can manage user permissions and customize request handling to meet your application’s needs.
[…] Custom Middleware in Laravel 11 […]
[…] Custom Middleware in Laravel 11 […]
[…] Custom Middleware in Laravel 11 […]