Home > Enterprise >  Why this Implicit Binding is not working? - Laravel
Why this Implicit Binding is not working? - Laravel

Time:09-21

I'm using Laravel 9. I have a problem, i wil appreciate any help.

I Have a Model named Entity, a controller EntityControler, and a FormRequest UpdateEntityRequest.

My API Routes looks like:

    Route::apiResource('entities', EntityController::class);

so i have show, create, store, update, delete... routes.

This is muy update method in EntityController (without the code/not important now)

public function update(UpdateEntityRequest $request, Entity $entity)
{
   return $entity;
}

the update method works perfect. But I want another update method for only a section and here starts the problem.

This is my new API Routes:

    Route::apiResource('entities', EntityController::class);
    Route::patch('/entities/{id}/{section}',[EntityController::class, 'updateSection' ]);

And this is the new method in the controller(without code yet):

public function updateSection( UpdateEntityRequest $request,Entity $entity, $section)
{
    return $entity;
}

But this last method return [] insted of the Entity and the update method works. WHY? I change de uri in Postman for update PUT {{baseUrl}}/entities/1 and for updateSection {{baseUrl}}/entities/1/1 .

Why does work in update and not in updateSection?

PD: This method work, and give the id, and I can create a Entity from this: public function updateSection( UpdateEntityRequest $request, $entity, $section) { return $entity; } But this is not what I want. Any idea why this happen?

CodePudding user response:

please make sure your uri segment is same as the variable name in the controller, in your case replace id with entity

Route::patch('/entities/{entity}/{section}',[EntityController::class, 'updateSection' ]);

for more please see documentation

CodePudding user response:

Make the route param name consistent in your route api.php and your function updateSection in EntityController

Route::patch('/entities/{entity}/{section}',[EntityController::class, 'updateSection' ]);

and

public function updateSection( UpdateEntityRequest $request,Entity $entity, $section)
{
    return $entity;
}
  • Related