Explicit Binding In Laravel

Hello there! Hope you are doing well. Today in this article we are going to explore how to do the explicit binding in laravel.

When we want to do model binding we are not required to use laravel’s implicit,convention-based model resolution instead we can define how the route corresponds to the model. To do so you can use the model method of the router and specify the class for a given parameter

Define your explicit bindings at top of your boot method of RouteServiceProvider class

First, you need to make one model after that use that model in the file which contains the boot method.

For example, let’s say we have one user model and we want to bind {user} parameters to the user model. To do so paste this code to in your boot method

use App\Models\User;
use Illuminate\Support\Facades\Route;
 
/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::model('user', User::class);
 
    // ...
}

Now define a route that contains {user} parameters in your routs file.

use App\Models\User;
 
Route::get('/users/{user}', function (User $user) {
    //
});

We have successfully bound all {user} parameters with the App/Models/User model, and instances of that class will be injected into the route.

Now when a request to users/1  will inject the User instance from the database who has ID 1. If not found in the database then automatically 404 response gets generated.

Thanks for reading.

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories