haakym
haakym

Reputation: 12358

Laravel Middleware parameters from Controller constructor

I'm wondering how I can set up middleware using a controller constructor and also reference middleware parameters as I've done successfully in my routes file.

I have this working fine in routes.php:

Route::group(['middleware' => 'user-type:user'], function () {
  // routes
});

Now I want to do this within a controller constructor, but I'm getting some issues...

public function __construct()
{
    $this->middleware = 'event-is-active:voting';
}

And when I visit a link with the above applied I get the following error:

ErrorException in ControllerDispatcher.php line 127:
Invalid argument supplied for foreach()

Of course I'm doing this wrong - I couldn't see how to do it in the docs and reading the source didn't help, but perhaps I overlooked something. So I'm wondering what is the right way and is it even possible? Any help would be most appreciated, thanks!

Upvotes: 1

Views: 5247

Answers (2)

Ahesanali Suthar
Ahesanali Suthar

Reputation: 341

You are using wrong syntax for setting middleware from controller constructor.

First of all you have to use laravel 5.1 to use middleware parameter.

Now you can set middleware in controller in constructor only.

Like

function __construct()
{
    $this->middleware('event-is-active:voting');//this will applies to all methods of your controller
    $this->middleware('event-is-active:voting', ['only' => ['show', 'update']]);//this will applies only show,update methods of your controller

}

Please note that in above code show and update are the example name. you have to write actual name which you are using in your controller.

Let say you are using 1. getShowUser($userId) 2. postUpdateUser($userId)

than you have to apply middleware in these methods as mentioned below:

function __construct()
{
    $this->middleware('event-is-active:voting', ['only' => ['getShowUser', 'postUpdateUser']]);

}

Upvotes: 3

Ali Nazari
Ali Nazari

Reputation: 1438

Try this

function __construct()
{
    $this->middleware('user-type:param1,param2', ['only' => ['show', 'update']]);
}

Upvotes: 1

Related Questions