Laravel 12 Middleware Alias Register and Usage
Laravel 12 has implemented different way of registering middleware and it's alias. We can register middleware class from bootstrap/app.php file. Middleware alias can be used to protect routes or controllers. This tutorial is also applicable for laravel 11 also. In this article we will show, how to use create middleware and use from route file as well as from controller.
Here are the steps to follow to register Middleware and It's alias
- Install Laravel 12 Empty Project
- Make Middleware Class
- Register Middleware in App
- Use Middleware in Route
- Use Middleware in Controller
1 - Install Laravel 12 Empty Project
For tutorial purpose are going to install a fresh new empty laravel 12 project. We can also use this code example in our existing project built using laravel 11 or laravel 12 or even newer versions.
composer create-project --prefer-dist laravel/laravel laravel12-middleware 12.* cd laravel12-middleware
2 - Make Middleware Class
We will create a middleware called AccessRestrictionMiddleware and it will register this after successful creation. After running below command middleware will be created inside app/Http/Middleware directory
php artisan make:middleware AccessRestrictionMiddleware
AccessRestrictionMiddleware
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AccessRestrictionMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $allowedIp = [
            "127.0.0.1",
            "192.168.1.2",
            "220.110.10.15",
        ];
        // Check if the user allowed to access with ip
        if (!in_array($request->ip(), $allowedIp)) {
            abort(403, 'Unauthorized action.');
        }
        return $next($request);
    }
}3 - Register Middleware
Laravel has changed the way of registering middleware and it's class alias regrations. According to latest documentation of laravel 12, we will have to register middleware in bootstrap/app.php file; After that, we will be able to use middleware in our whole application. For now we are using ip access control middleware to restrict specific ip address. We can modify according to need. We have used class alias name as access; We can give our own name and use.
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([
            'access' => \App\Http\Middleware\AccessRestrictionMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();4 - Use Middleware in Route
As we have created a class alias and registered middleware in our application, so we are ready to use middleware in route file as well. Here is the way of using middleware alias in routes/web.php file
Use in Route
use Illuminate\Support\Facades\Route;
Route::get('/page', function () {
    return "Welcome, Editor!";
})->middleware('access');Use in Route Group
Route::middleware(['access'])->group(function () {
    Route::get('/route-one', function () {
        // Route logic for /route-one
    });
    Route::get('/route-two', function () {
        // Route logic for /route-two
    });
});5 - Use Middleware in Controller
namespace App\Http\Controllers;
use App\Http\Middleware\YourMiddleware;
class TestController extends Controller
{
    public function __construct()
    {
        $this->middleware(['access']);
    }
    public function someMethod()
    {
        // Controller logic
    }
}Hope that, this middleware alias article will help you to create your own middleware with alias feature. Stay tune to programmingmindset.com
