skip to Main Content

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


  1. That’s route model binding behavior that is built in Laravel (https://laravel.com/docs/10.x/routing#route-model-binding):

    When injecting a model ID to a route or controller action, you will often query the database to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user’s ID, you can inject the entire User model instance that matches the given ID.

    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:

    use AppHttpControllersUserController;
    use AppModelsUser;
     
    // Route definition...
    Route::get('/users/{user}', [UserController::class, 'show']);
     
    // Controller method definition...
    public function show(User $user)
    {
        return view('user.profile', ['user' => $user]);
    }
    

    If you are interested of how it works automatically in depth, I recommend you take a look at these files in Laravel source code:

    Login or Signup to reply.
  2. 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.

    public function show(Customer $customer): IlluminateHttpJsonResponse
    {
        return response()->json($customer);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search