Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'auth' Middleware with Route::resource

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);
}
like image 375
itsazzad Avatar asked Oct 29 '25 05:10

itsazzad


2 Answers

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

like image 85
itsazzad Avatar answered Oct 31 '25 21:10

itsazzad


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

Edit

Apparently before filters only work with resource routes when you wrap a group around it. See the OPs answer for an example...

like image 38
lukasgeiter Avatar answered Oct 31 '25 22:10

lukasgeiter