Route Model Binding in Laravel 5.5

Often in your application you will come across a requirement where you need to get the details from the database from a particular table with the unique id that is passed into the URL.

If you are using Eloquent, you will capture the unique id in your controller and use particular Model to find the particular row from the database and get into your controller.

Let’s say you are working on a Task Application, where user can create, update, read and delete tasks.

To read a paricualr task from the database you will create a route something like.

Livewire Component Library
Route::get('/tasks/{id}', 'TaskController@show');

The show method of TaskController expects an $id to fetch the Task detail from the database.

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
    public function show($id)
        $task = \App\Task::find(1);
        return view('',compact('task',$task));

This is the conventional way of getting the data from database by passing unique id into the URL and then using the Eloquent methods to fetch the details.

Route-Model Binding

With route model binding Laravel simplfies the job for you. With implicit binding you just need object directly into your controller and make sure the name of URL parameter in the route is similar to the object name you are passing in your controller.

Laravel will do the implicil binding , fetch the required details from the database and you can use the same object to pass it to the view.

The Rotue will look something like this.

Route::get('/tasks/{task}', 'TaskController@show');

And instead of id , you need to pass the object of your Model class directly into the controller method.

    public function show(Task $task)
        return view('',compact('task',$task));

That’s it ! Laravel will take care of the internals, Use the similar approach whenever you need to get the particular data using Model.


Site Footer