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:
Route::resource('photo', 'PhotoController');
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.
Route::resource('photo', 'PhotoController', ['names' => [
'create' => 'photo.build'
]]);
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:
/photo/{photo}
And you need to deal with $photo variable.
If, for whatever reason, you want to override it to $user_photo, you easily can:
Route::resource('photo', 'PhotoController', ['parameters' => [
'photo' => 'user_photo'
]]);
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.
No comments or questions yet...