Sam
Sam

Reputation: 997

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?

Upvotes: 1

Views: 1849

Answers (2)

JeuneApprenti
JeuneApprenti

Reputation: 527

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

Upvotes: 2

Tharaka Dilshan
Tharaka Dilshan

Reputation: 4499

You cannot give a 'name' to a resource route. but you can give names to each method in the resource controller separately.

to do so name() function required 2 parameters.

  1. method name
  2. name for that method route.

,

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

Upvotes: 2

Related Questions