1 year ago

#247289

test-img

SuperDJ

Is it possible to make a one of many middleware in Laravel?

I have the following middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class OneOfMiddleware
{
    public function handle( Request $request, Closure $next, ...$middlewares )
    {
        $pass = false;
        foreach( $middlewares as $middleware )
        {
            if( app()->bound( $middleware ) )
            {
                $pass = app( $middleware )->handle( $request, $next );
            }
        }

        if( !$pass )
        {
            abort( 401 );
        }

        return $next( $request );
    }
}

Usage:

'middleware' => [
   \App\Http\Middleware\OneOfMiddleware::class => [
      \Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
      'auth'
   ]
];

The idea behind the OneOfMiddleware is that one of the provided $middlewares must be successful for it to pass. So in case of the example either the request must be from a authenticated Passport client or authenticated by web. However when using the OneOfMiddleware I get the below error. It is already thrown on the first line of the middleware.

TypeError: Illegal offset type in isset or empty in file /home/cadixcas/domains/dev.cadixcas.nl/public_html/vendor/laravel/framework/src/Illuminate/Routing/Router.php on line 1316 That points to the following:

public static function uniqueMiddleware(array $middleware)
    {
        $seen = [];
        $result = [];

        foreach ($middleware as $value) {
            $key = \is_object($value) ? \spl_object_id($value) : $value;

            if (! isset($seen[$key])) { // This line
                $seen[$key] = true;
                $result[] = $value;
            }
        }

        return $result;
    }

Is is possible to make a one of many middleware? If so how can I prevent the thrown error?

php

laravel

laravel-middleware

0 Answers

Your Answer

Accepted video resources