17

Stackers! I'm currently learning laravel5 and I love it, but I'm struggling with one thing. Since Laravel 5 we have Middleware which we can use in controller's construct function, like this:

Controller file:

public function __construct()
{
    $this->middleware('admin', ['only' => 'create']);
}

Now what I want is to define HERE^ (not in routes file) middleware to be used in multiple views, like 'create', 'edit' and 'show'. defining

public function __construct()
{
            $this->middleware('admin', ['only' => 'create|edit|show']);
}

Unfortunately does not work. I'd rather not use routes. Any ideas, dear friends?

Talky
  • 173
  • 1
  • 4
  • Hi, how do i use this for two roles, lets say Admin have access to all methods and Manager only have access to create, edit, show how can i do that ? how to write middleware for something like that. – Chanuka Asanka May 21 '15 at 06:33

1 Answers1

27

Simply pass an array instead of a string with | delimiter:

public function __construct()
{
    $this->middleware('admin', ['only' => ['create', 'edit', 'show']]);
}
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • Hi, how do i use this for two roles, lets say Admin have access to all methods and Manager only have access to create, edit, show how can i do that ? how to write middleware for something like that. – Chanuka Asanka May 21 '15 at 06:32
  • 1
    @ChanukaAsanka Simply call `$this->middleware()` twice – lukasgeiter May 21 '15 at 07:15
  • ok .. you mean i should have two middlewar called Admin & Manager. but i don't know how to handle that in handle method.. public function handle($request, Closure $next) { if (\Auth::user()->role == 'Manager') { return true; } return $next($request); } can you provide example. basically i don't need to give permission to delete for Manager – Chanuka Asanka May 21 '15 at 08:17
  • @ChanukaAsanka This isn't really related to this question anymore. Please ask a question yourself – lukasgeiter May 21 '15 at 08:42
  • Sure I'll post. Thanks for reply – Chanuka Asanka May 21 '15 at 09:37
  • You can do this ... $this->middleware('auth'); $this->middleware('customAuth'); .... and so on – Andy Aug 22 '17 at 18:52