Model binding

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.

Read revisited

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.

List revisited

Similarly, for the list method, we inject the type-hinted model as follows:

public function index(Accommodation $accommodation)
{
    return $accommodation;
}

Update revisited

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'),
}

Delete revisited

Also, the destroy method looks like this:

public function destroy(Accommodation $accommodation)
{
    $accommodation->delete();
    return response('Deleted.', 200)
        ->header('Content-Type', 'text/html'),
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset