Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide an example of using the alias() method with custom middleware in Laravel 11


Can you provide an example of using the alias() method with custom middleware in Laravel 11


Sure, here's an example of using the `alias()` method to define a custom middleware alias in Laravel 11:

1. Create a new middleware using the `artisan` command:

bash
php artisan make:middleware LogRequests

This will create a new middleware class `LogRequests` in the `app/Http/Middleware` directory.

2. Open the `LogRequests` middleware and add your custom middleware logic:

php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class LogRequests
{
    public function handle(Request $request, Closure $next)
    {
        // Log the request
        logger()->info('New request received', [
            'url' => $request->url(),
            'method' => $request->method(),
        ]);

        return $next($request);
    }
}

3. In the `bootstrap/app.php` file, use the `alias()` method to define an alias for your custom middleware:

php
return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'logRequests' => \App\Http\Middleware\LogRequests::class,
        ]);
    })
    // Other configuration
    ->create();

In this example, we're defining an alias `'logRequests'` for the `\App\Http\Middleware\LogRequests` class.

4. Now, you can use the alias when applying middleware to routes or groups:

php
Route::get('/example', function () {
    // ...
})->middleware('logRequests');

Or, you can apply the middleware to a group of routes:

php
Route::middleware('logRequests')->group(function () {
    Route::get('/example1', function () {
        // ...
    });

    Route::get('/example2', function () {
        // ...
    });
});

By using the `alias()` method, you can define short, descriptive names for your middleware, making your route and middleware configuration more readable and maintainable.

Remember to replace `\App\Http\Middleware\LogRequests::class` with the actual namespace of your custom middleware class if it differs.

Citations:
[1] https://www.itsolutionstuff.com/post/how-to-customize-default-middleware-in-laravel-11example.html
[2] https://laracasts.com/discuss/channels/laravel/here-to-declare-aliases-on-laravel-11
[3] https://laravel.com/docs/11.x/middleware
[4] https://laracasts.com/discuss/channels/laravel/laravel-11-providers-and-alias-in-appphp
[5] https://dev.to/tanzimibthesam/laravel-10-laravel-11-comparison-changes-2g24