David Sojka
David Sojka

Reputation: 83

How to rename route key with model binding in PHP Laravel 8 (incorrect plurals)?

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:

  1. keep the URI in the correct plural (i.e. /fields-of-study),
  2. keep the show() parameter name in the correct singular (i.e. $fieldOfStudy) and
  3. don't mess the model-binding mechanism for typed parameters like show(FieldOfStudy $fieldOfStudy)?

Thank you :)

Upvotes: 3

Views: 1351

Answers (1)

Maksim
Maksim

Reputation: 2957

You can manipulate Laravel explicit binding:

RouteServiceProvider.php

public function boot()
{
    Route::model('fields-of-study', FieldOfStudy::class);
}

Upvotes: 1

Related Questions