Unable to make my own 'api' middleware alias in order to use a dependency with laravel 11.

Updated: Jan 26, 2025

Unable to make my own 'api' middleware alias in order to use a dependency with laravel 11.

To create an alias for your custom middleware in Laravel 11, follow these steps:

  1. Create a new middleware class.

Assuming you have a dependency that you want to use in your middleware, let's call it MyDependencyMiddleware. First, create a new middleware class with the name MyDependencyMiddleware.php in the app/Http/Middleware directory.

<?php

namespace App\Http\Middleware;

use Closure;
use YourVendor\YourPackage\YourDependency; // Import your dependency here

class MyDependencyMiddleware
{
    protected $dependency;

    public function __construct(YourDependency $dependency)
    {
        $this->dependency = $dependency;
    }

    public function handle($request, Closure $next)
    {
        // Your middleware logic here

        return $next($request);
    }
}

Replace YourVendor, YourPackage, and YourDependency with the actual vendor, package, and dependency names.

  1. Register the middleware.

Next, register the middleware in the app/Http/Kernel.php file. Add the middleware to the $routeMiddleware array.

protected $routeMiddleware = [
    // ...
    'my.dependency' => \App\Http\Middleware\MyDependencyMiddleware::class,
];
  1. Use the alias in your routes or controllers.

Now you can use the alias my.dependency in your routes or controllers to apply the middleware to a specific route or controller action.

// In a route file
Route::get('/example', 'ExampleController@index')->middleware('my.dependency');

// In a controller
class ExampleController extends Controller
{
    public function index()
    {
        // Your controller logic here
    }

    public function __construct()
    {
        $this->middleware('my.dependency');
    }
}

That's it! You have created a custom middleware alias in Laravel 11 and used it to apply a dependency to a route or controller action.