1

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!

2 Answers 2

3

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']]);

}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your reply. How is my syntax wrong? The only difference between my code and yours is the public identifier on the construct method. I am using Laravel 5.1. I want it to apply to all of my methods hence why I didn't restrict it.
i find below syntax is wrong. $this->middleware = 'event-is-active:voting';
public identifier is required for constructor. How ever i have just demonstrated the code to explain you.
Checkout syntax for controller middleware in documentation. laravel.com/docs/5.1/controllers#controller-middleware
Sometimes it happens to me also.
|
1

Try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.