Search code examples
laravelmiddlewarelaravel-middlewarelaravel-11

Laravel middlewares


I created a laravel middleware with this code:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Containers\Modals\Models\Modal;

class ModalsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $modalNames): Response
    {
        $modals = explode(',', $modalNames);
        foreach ($modals as $modalName) {
            $modal = Modal::where('slug', $modalName)->first();
            if (!$modal->enabled) {
                abort(404);
            }
        }
        return $next($request);
    }
}

Then I updated Kernel.php:

**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array<string, class-string|string>
     */
    protected $routeMiddleware = [
       ...,
       'modals' => \App\Http\Middleware\ModalsMiddleware::class,
    ];

And for my route group I added the following:

Route::group([
    'prefix' => 'api/v1/routeName',
    'middleware' => ['auth:api', 'modals:AModalName']
], function() {...});

Then I ran: php artisan optimize && php artisan config:cache && php artisan cache:clear && php artisan config:clear && composer dump-autoload And stoped serve then I re-ran the app

However I had this error:

"message": "Target class [modals] does not exist.",
    "exception": "Illuminate\\Contracts\\Container\\BindingResolutionException",

How can I fix that?


Solution

  • In Larave 11 you have to register your middleware in the bootstrap/app.php file.

    ->withMiddleware(function (Middleware $middleware) {
            $middleware->alias([
                'modals' => \App\Http\Middleware\ModalsMiddleware::class,
            ]);
        })
    

    For more details visit the official documentation.

    Here is what the full code looks like.

    <?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([
                'modals' => \App\Http\Middleware\ModalsMiddleware::class,
            ]);
        })
        ->withExceptions(function (Exceptions $exceptions) {
            //
        })->create();