Now, we can use a technique called model binding to clean up the code even more:
public function boot(Router $router) { parent::boot($router); $router->model('accommodations', 'MyCompanyAccommodation'), }
In app/Providers/RouteServiceProvider.php
, add the $router->model()
method that accepts the route as the first argument and the model that will be bound as the second argument.
Now, our
show
controller method looks like this:
public function show(Accommodation $accommodation) { return $accommodation; }
When /accommodations/1
is called, for example, the model that corresponds to that ID will be injected into the method, allowing us to substitute the find method.
Similarly, for the list
method, we inject the type-hinted model as follows:
public function index(Accommodation $accommodation) { return $accommodation; }
Likewise, the
update
method now looks like this:
public function update(Accommodation $accommodation) { $input = Input::json(); $accommodation->name = $input->get('name'), $accommodation->description = $input->get('description'), $accommodation->location_id = $input->get('location_id'), $accommodation->save(); return response($accommodation, 200) ->header('Content-Type', 'application/json'), }