Search code examples
phplaravellaravel-routing

Laravel resource route with name gives error


I followed a tutorial to add middleware checking if a user is admin when loading a page. It works for normal view routes, e.g.

Route::get('/admin/something', 'AdminController@admin_something')
    ->middleware('is_admin')
    ->name('admin');

But I now have a resource route and get an error when I add the name and middleware to the route. So this works with no auth:

Route::resource('thingies', 'ThingyController');

But with this:

Route::resource('thingies', 'ThingyController')
    ->middleware('is_admin')
    ->name('admin');

I get an error:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Too few arguments to function Illuminate\Routing\PendingResourceRegistration::name(),
  1 passed in /var/www/routes/web.php on line 24 and exactly 2 expected

What do I need to do differently to add this auth to a resource route?


Solution

  • You can't name your route "admin" with ->name('admin'); at the end of your resource route because it concerns all CRUD routes in one statement and Laravel build-in system has already named them.

    You're on the good way, just delete the last line like so, it should works :

    Route::resource('thingies', 'ThingyController') ->middleware('is_admin');