Laravel 从模型数据生成命名路由

我想对我的 Laravel URL 进行 SEO,所以我想更改www.example.com/posts/32www.example.com/posts/how-to-name-routes

我看到我可以通过在路由上链接name()方法来手动命名路由,但我希望name从帖子的标题中自动填充。然而,标题包含空格所以我的Post对象会有,title 'How to name routes'但 URL 会是www.example.com/posts/how-to-name-routes

我需要实现我自己的字符串操作系统还是 Laravel 已经处理了?


白猪掌柜的
浏览 201回答 2
2回答

芜湖不芜

您可以为 Posts 表添加一个唯一的slug列,然后将其用作路由中的参数,例如'/posts/{slug}'.您可以在 Post 模型中为此添加一个 mutator:public function setTitleAttribute($title){    $this->attributes['slug'] = str_slug($title);    $this->attributes['title'] = $title;}

月关宝盒

我的建议是在您的Post模型上实现一个 slug 字段,并将其用作路由模型绑定的键。要对帖子标题进行 slugify,请使用 Laravel 的 Muttators 将帖子标题转换为 URL 友好的 slug。为确保 slug 是唯一的,您可以将时间戳附加到 slug,在删除列冲突的同时保留 SEO。    /**     * Set the post's slug.     *     * @return void     */    public function setSlugAttribute()    {        $this->attributes['slug'] = Str::slug($this->attributes['title']) . dechex(time());    }创建 slug 字段后,您可以通过覆盖模型中的getRouteKeyName方法将其绑定到路由Post。    public function getRouteKeyName()    {        return 'slug';    }你的路线会变成这样    Route::get('posts/{post}', 'PostsController@getPost');参考:路由模型绑定: https : //laravel.com/docs/5.8/routing#route-model-binding Slug Helper: https: //laravel.com/docs/5.8/helpers#method-str-slug Eloquent Mutators: https://laravel.com/docs/5.8/eloquent-mutators
打开App,查看更多内容
随时随地看视频慕课网APP