Sorry if my question is kinda stupid, but i do not understand how show method returns me customer by id, where the functional is given?
my api router
Route::group(['prefix' => 'v1', 'namespace' => 'AppHttpControllersAPIV1'], function(){
Route::apiResource('customers', CustomerController::class);
});
show() method in controller
public function show(Customer $customer)
{
return $customer;
}
if i call http:mydomain/api/v1/customers/1
it returns me customer with id 1.
What is a missing element of chain, where i get Customer $customer element?
2
Answers
That’s route model binding behavior that is built in Laravel (https://laravel.com/docs/10.x/routing#route-model-binding):
What it does is that it checks if you have model with given ID that matches your route path, and if there is, it automatically injects that model to your controller, where you can use it.
Basically, it is performed automatically, but you can use implicit route model binding (https://laravel.com/docs/10.x/routing#implicit-binding) to modify that logic:
For example:
If you are interested of how it works automatically in depth, I recommend you take a look at these files in Laravel source code:
Because it is an api, I recommend returning it as json. The default model already returns all the attributes of the model when used this way.