【问题标题】:Laravel generate named routes from model dataLaravel 从模型数据生成命名路由
【发布时间】:2023-03-12 21:43:01
【问题描述】:

我想对我的 laravel 网址进行 SEO 优化,所以我想将 www.example.com/posts/32 更改为 www.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 已经处理了这个系统?

【问题讨论】:

标签: php laravel routes


【解决方案1】:

您可以为您的 Posts 表添加一个唯一的 slug 列,然后将其用作路由中的参数,例如'/posts/{slug}'.

您可以在 Post 模型中为此添加一个 mutator:

public function setTitleAttribute($title)
{
    $this->attributes['slug'] = str_slug($title);
    $this->attributes['title'] = $title;
}

【讨论】:

    【解决方案2】:

    我的建议是在您的 Post 模型上实现一个 slug 字段,并将其用作路由模型绑定的键。

    要对帖子标题进行 slug 化,请使用 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 字段后,您可以通过覆盖 Post 模型中的 getRouteKeyName 方法将其绑定到路由。

    
        public function getRouteKeyName()
        {
            return 'slug';
        }
    
    

    你的路线会变成这样的

    
        Route::get('posts/{post}', 'PostsController@getPost');
    
    

    参考资料: 路由模型绑定: https://laravel.com/docs/5.8/routing#route-model-binding 蛞蝓助手: https://laravel.com/docs/5.8/helpers#method-str-slug 雄辩的突变体: https://laravel.com/docs/5.8/eloquent-mutators

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多