关于Laravel 7 的简单隐式路由模型绑定

Laravel 的下一个主要发行版本 ,你可以直接在路由定义中自定义隐式路由模型绑定:

Route::get('/posts/{post:slug}', function (Post $post) {

    // ...

});

  

目前,使用 Laravel 6,下文中的需求需要你像这样在模型上定义一个 getRouteKeyName() 方法:

<?php

class Post extends Model

{

    /**

     * Get the route key for the model.

     *

     * @return string

     */

    public function getRouteKeyName()

    {

        return 'slug';

    }

}

  

你仍能使用 getRouteKeyName() 方法;然而,我认为直接在路由中自定义它会更流畅。

可能你会有多个希望以不同方式绑定的路由。比如,前台路由用 slugs 去显示 posts ,后台则希望以 id 管理 posts

Route::get('/posts/{post:slug}', function (Post $post) {

    // ...

});

// 或者你在这儿可以用默认的`{post}`

Route::get('/admin/posts/{post:id}/edit', function (Post $post) {

    // ...

});

  

如果你开始尝试自定义隐式路由模型绑定,你可以安装开发版本的 Laravel

laravel new example --dev

  

以上就是关于Laravel 7 的简单隐式路由模型绑定的详细内容

更多学习内容请访问:

腾讯T3-T4标准精品PHP架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)

原文地址:https://www.cnblogs.com/a609251438/p/12653163.html