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.

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');
    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.

Get The best In Web dev

Get The best In Web dev

Join dunebook and recieve best in Angular, React, Vue, Python, Java & more. Directly to your inbox once a week FREE !

You have Successfully Subscribed!

Pin It on Pinterest