laravel resource controllers

Resourceful controllers: overriding route names and parameters

Resource controllers are amazing tool to work with CRUD functions in Laravel. But what if their default functionality isn’t 100% suitable and you want to override some defaults? Let’s see what you can do.

Overriding route names

Default functionality in routes:

It will assume that controller will have these methods:

  • index()
  • create()
  • store()
  • edit()
  • update()
  • show()
  • destroy()

And the same will apply to route names – they will be assigned as photo.create, photo.show etc. So what if you want to override them? There’s a parameter for that.

In this case, photo.create will be replaced by photo.build, which now you can call in the links.


Overriding route parameters

Another assumption of Resource controllers are the variables for methods like show() or edit(). By default, the case of Route::resource(‘photo’, ‘PhotoController’); will generate route like this:

And you need to deal with $photo variable.
If, for whatever reason, you want to override it to $user_photo, you easily can:

I know that this overriding is probably quite an edge-case, but it was news for me, so decided to share.

This is one of the places in documentation which people don’t get to, until they need to solve that actual problem. And then they usually go to forums for the answer. Hopefully now they will google and land on this article.

Link to the official documentation.

Want more tips and articles like this?
Subscribe to our weekly newsletter - comes out every Thursday!
Join 1200+ Laravel professionals who read the issue weekly.

One thought on “Resourceful controllers: overriding route names and parameters

Leave a Reply

Your email address will not be published. Required fields are marked *