Create Custom Middleware in Laravel 11

Create 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.

Step 1: Install Laravel 11

First, we’ll install laravel 11 using the following command.

composer create-project --prefer-dist laravel/laravel test-11        

Step 2: Create Middleware

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);
    }
}        

Step 3: Register Middleware

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();        

Step 4: Apply Middleware

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';
    });
});        
Irfan Danish

Student at Universiti Teknikal Malaysia Melaka

5 天前

Hi, I'm new to Laravel and I have a question about this post. Is it okay if I don't put step number 3, otherwise why is it needed?

回复
?? Franco Jofré

Full Stack Developer | CTO | Tech Recruiter

4 个月

Thanks a lot, there isn't much information about alias in middlewares in Laravel 11

回复
Faithful Eromosele

Software Developer | MVC Architect (Express, Nest.js, Laravel) | React/Next.js Developer | React Native Maestro | Problem Solver & Debugging Enthusiast

5 个月
回复
Jay Millena

Laravel Web Developer

5 个月

Thank you brother, well explained.

回复
Ebenezer Narh-ngwah

Founder & CEO | Software Development, Entrepreneurship

6 个月

Perfect job, worked

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了