Clean up your code in laravel using model binding

we all have faced a situation where our code becomes bugy and difficult to understand  so ,Here we will use a technique called model binding to clean up the code even more:

public function boot(Router $router)
    $router->model('accommodations', '\MyCompany\Accommodation');

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.

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');
    return response($accommodation, 200)
    ->header('Content-Type', 'application/json');

Delete revisited

Also, the destroy method looks like this:

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

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest