Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Defining middleware for multiple routes in controller file

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?

like image 364
Talky Avatar asked Feb 21 '15 11:02

Talky


People also ask

What middleware groups does Laravel come with?

Out of the box, Laravel comes with weband apimiddleware groups that contain common middleware you may want to apply to your web UI and API routes: /** * The application's route middleware groups.

How to add multiple routes in Laravel 5?

Laravel 5 multiple routes files. 1. create two route files routes.web.php and routes.api.php. 2. edit the RouteServiceProvider.php file to look like the code below: (Note: you can add as many routes as you want, just follow the same logic.)

How do I add middleware to a Laravel route?

You may do this using the $middlewareGroupsproperty of your HTTP kernel. Out of the box, Laravel comes with weband apimiddleware groups that contain common middleware you may want to apply to your web UI and API routes: /** * The application's route middleware groups.

What is resource routing in Laravel?

Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for "photos" stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:


1 Answers

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

public function __construct()
{
    $this->middleware('admin', ['only' => ['create', 'edit', 'show']]);
}
like image 200
lukasgeiter Avatar answered Sep 29 '22 00:09

lukasgeiter