Reputation: 7277
How can I use middleware with resources?
Route::resource('myitem', ['middleware' => 'auth', 'uses' => 'App\\Controllers\\MyitemsController']);
Just followed https://laracasts.com/discuss/channels/general-discussion/struggling-with-routeresource-and-auth-middleware but unfortunately could not solve.
Getting error:
ErrorException (E_UNKNOWN)
Array to string conversion
Open: /vendor/laravel/framework/src/Illuminate/Routing/Router.php
protected function getResourceAction($resource, $controller, $method, $options)
{
$name = $this->getResourceName($resource, $method, $options);
return array('as' => $name, 'uses' => $controller.'@'.$method);
}
Upvotes: 4
Views: 4384
Reputation: 1
Better solution
Use middleware instead of before
Route::group(['middleware' => 'auth'], function(){
Route::resource('myitem', 'MyitemsController');
});
You can check if it's ok with:
php artisan route:list
Upvotes: 0
Reputation: 11108
How to do this in Laravel 5. The Answer you have been waiting for.
Use middleware
instead of before
Route::group(array('middleware' => 'auth'), function()
{
Route::resource('user', 'UserController',
['only' => ['edit']]);
}
To check if the route is setup, run:
php artisan route:list
which should show the following:
GET|HEAD | user/{user}/edit | user.edit | App\Http\Controllers\UserController@edit | auth
Note auth
instead of guest
Upvotes: 0
Reputation: 11
I just came up against this and found the easiest way is to add the middleware straight to the controller.
I found my answer here: http://laravel.com/docs/master/controllers
class MyitemsController extends Controller {
/**
* Instantiate a new MyitemsController instance.
*/
public function __construct()
{
$this->middleware('auth');
}
}
Upvotes: 0
Reputation: 153150
Middleware is a new feature of Laravel 5. In Laravel 4, filters where something similar. So instead of using the key middleware
you should use before
or after
. Also, and that's where the error comes from, the second argument of Route::resource
should be the controller name as string and the third one is an array of options:
Route::resource('myitem', 'App\\Controllers\\MyitemsController', ['before' => 'auth']);
Apparently before filters only work with resource routes when you wrap a group around it. See the OPs answer for an example...
Upvotes: 3
Reputation: 7277
Using filter with resource was not working that why had to use Route::group
Route::group(array('before' => 'auth'), function()
{
Route::resource('myitem', 'App\\Controllers\\MyitemsController');
});
https://stackoverflow.com/a/17512478/540144
Upvotes: 4