Reputation: 83
I have a Laravel 8 project where I have a model called FieldOfStudy
, but the problem is that the plural of this class's name should be fields of study instead of field of studies. That causes a problem when creating an API endpoint with the following route:
Route::apiResource('fields-of-study', FieldOfStudyController::class);
The thing is, that I have a resource controller's method FieldOfStudyController::show()
like this:
public function show(FieldOfStudy $fieldOfStudy)
{
dd($fieldOfStudy);
}
This will show me, that $fieldOfStudy
contains a "blank" model, not the desired instance from the database. When I checked the route parameters, I found out, that the id of the model is stored as fields_of_study
instead of field_of_study
.
I tried to rename the parameter (didn't work - binding fails):
Route::apiResource('fields-of-study', FieldOfStudyController::class)->parameter('fields_of_study','field_of_study');
When I rename the parameter of the show()
method, it works, but it's not really pretty:
public function show(FieldOfStudy $fieldsOfStudy) { }
How can I properly adjust my code to:
/fields-of-study
),show()
parameter name in the correct singular (i.e. $fieldOfStudy
) andshow(FieldOfStudy $fieldOfStudy)
?Thank you :)
Upvotes: 3
Views: 1351
Reputation: 2957
You can manipulate Laravel explicit binding:
RouteServiceProvider.php
public function boot()
{
Route::model('fields-of-study', FieldOfStudy::class);
}
Upvotes: 1