I'm trying to find a model either by its ID or unique ID string (not the primary key) with type hinting, so I don't repeat lines for finding inside the controller.
Imagine that I have a class called Activity and I have a route:
Route::get('activities/{id}', 'activityController@view');
And in the Controller
public function View(Activity $id){}...
How does the Service container resolve $id? I've overridden the find() and findOrFail() methods of the model, and it doesn't return the model with type hinting alone.
Sorry if this is a dumb question :)
Thanks guys.
CodePudding user response:
You can use the route service provider and bind the model to the route
/***RouteServiceProvider**/
public function boot(){
Route::model('activity',Activity::class);
}
Then you would have your route link defined as
Route::get('activities/{activity}','activityController@view');
Where {activity} is the id of the activity.
Here is the documentation on explicit binding. https://laravel.com/docs/8.x/routing#explicit-binding There is also implicit binding if you would like, however explicit is far more clear.
If you would like to resolve it via your custom callback, use the resolution found here https://laravel.com/docs/8.x/routing#customizing-the-resolution-logic
Happy Coding!