Laravel5.2 new feature series-implementation of implicit routing model binding

Source: Internet
Author: User
Laravel5.2 new feature series-implicit routing model binding feature Laravel5.1 provides the routing model binding feature, which is easier to implement in Laravel5.2.

1. basic use of routing model binding

We usually bind the model in URL routing as follows:

Route::group(['middleware' => ['web']], function () {    Route::get('/user/{id}',function($id){        $user = \App\User::findOrFail($id);        dd($user);    });});

I usually do this, but is it better to get the $ user instance directly by removing the findOrFail line? In fact, Laravel does achieve this purpose. add the following line of code in the boot method of RouteServiceProvider of the routing service:

public function boot(Router $router){    $router->model('user',User::class);    parent::boot($router);}

This means that whenever the route contains the user parameter, its ID value corresponds to an App \ User instance. This mechanism allows us to rewrite the above code as follows:

Route::group(['middleware' => ['web']], function () {    Route::get('/user/{user}',function($user){        dd($user);    });});
2. binding the implicit routing model

In Laravel 5.2, it is easier to bind a routing model. you only need to declare a parameter in the routing closure (or controller method) and keep the parameter consistent with the routing parameter, in this way, the parameter is automatically bound as a routing model for processing (you do not need to call the model method in RouteServiceProvider to declare the binding relationship ):

Route::group(['middleware' => ['web']], function () {    Route::get('/user/{user}',function(\App\User $user){        dd($user);    });});

The printed results are exactly the same as before.

3. some features of routing model binding

3.1 Custom Route model binding logic

If you want to customize the routing model binding logic to return the desired instance, you can pass a closure instead of a class name as the explicit binding (relatively implicit model binding, you need to define the binding relationship in the boot method of RouteServiceProvider called explicit binding). The second parameter is as follows:

public function boot(Router $router){    $router->bind('user',function($value){        return User::where('name',$value)->where('status',1)->first();    });    parent::boot($router);}

3.2 an error occurred while binding the custom routing model.

You can also pass a closure as the third parameter to customize the Exception thrown by binding the routing model (for example, when the corresponding model instance cannot be found ):

public function boot(Router $router){    $router->bind('user',User::class,function(){        throw new NotFoundHttpException;    });    parent::boot($router);}

3.3 modify the "route key" of the Eloquent model"

By default, Laravel uses the id field in the URL fragment to match the Eloquent model. However, if you want to customize this field, just like binding the custom routing model above, how can this problem be achieved?

Eloquent implements the Illuminate \ Contracts \ Routing \ UrlRoutable interface, which means that the Eloquent object has a getRouteKeyName () method. In this method, you can define the field used in the URL to match the model instance, the default value is id. you can override it in any Eloquent model:

class User extends Model {    public function getRouteKeyName()    {        return 'name';    }}

Now, you can bind an explicit or implicit routing model and customize the matching fields in the URL fragment.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.