Laravel 的下一个主要发行版本 ,你能够直接在路由定义中自定义隐式路由模型绑定:php
Route::get('/posts/{post:slug}', function (Post $post) { // ... });
目前,使用 Laravel 6,下文中的需求须要你像这样在模型上定义一个 getRouteKeyName() 方法:node
<?php class Post extends Model { /** * Get the route key for the model. * * @return string */ public function getRouteKeyName() { return 'slug'; } }
你仍能使用 getRouteKeyName() 方法;然而,我认为直接在路由中自定义它会更流畅。laravel
可能你会有多个但愿以不一样方式绑定的路由。好比,前台路由用 slugs 去显示 posts ,后台则但愿以 id 管理 posts架构
Route::get('/posts/{post:slug}', function (Post $post) { // ... }); // 或者你在这儿能够用默认的`{post}` Route::get('/admin/posts/{post:id}/edit', function (Post $post) { // ... });
若是你开始尝试自定义隐式路由模型绑定,你能够安装开发版本的 Laravelpost
laravel new example --dev
以上就是关于Laravel 7 的简单隐式路由模型绑定的详细内容学习
更多学习内容请访问:spa