Michael
Michael

Reputation: 576

Laravel 5.6 multiple middleware with except on 1 middleware

I have 2 middlewares for my controller, clearance & status.

I need all the clearance middleware on all my controller methods, and for the status middleware I need to excpet the following methods: index, create, store and destroy.

I do this in my controller but this applies the except for bot middleware.

$this->middleware(['clearance', 'status', ['except' => ['index', 'create', 'store', 'destroy']]]);

Is there a way to achieve my goal?

Upvotes: 0

Views: 3158

Answers (2)

MD. Jubair Mizan
MD. Jubair Mizan

Reputation: 1570

You can use Middleware Groups:

/**
 * The application's route middleware groups.
 *
 * @var array
*/
protected $middlewareGroups = [
   'web' => [
      \App\Http\Middleware\EncryptCookies::class,
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
      \Illuminate\Session\Middleware\StartSession::class,
      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
      \App\Http\Middleware\VerifyCsrfToken::class,
   ],

   'api' => [
      'throttle:60,1',
      'auth:api',
   ],

];

Also you can use many middlewares in __construct() method:

class UserController extends Controller{
  /**
   * Instantiate a new UserController instance.
   *
   * @return void
   */
  public function __construct(){
    $this->middleware('auth');

    $this->middleware('log', ['only' => [
        'fooAction',
        'barAction',
    ]]);

    $this->middleware('subscribed', ['except' => [
        'fooAction',
        'barAction',
    ]]);
  }
}

More: HTTP Controllers, HTTP Middleware

Upvotes: 0

Jerodev
Jerodev

Reputation: 33216

Yes, you can call the middleware function once for each middleware.

$this->middleware('clearance');
$this->middleware('status')->except(['index', 'create', 'store', 'destroy']);

Upvotes: 1

Related Questions