【问题标题】:Laravel Slug DuplicateLaravel 蛞蝓重复
【发布时间】:2020-02-17 20:13:39
【问题描述】:

当我尝试使用相同的 slug 创建帖子时,它通常也会在更新相同的问题时创建帖子 在这种情况下,我会为 post 复制 slugs

我搜索了很多关于这个问题但我没有得到任何答案

有什么办法解决这个问题吗?

型号

protected $fillable = [
    'title', 'slug', 'body',
];

控制器

    public function slug($string, $separator = '-') {
    if (is_null($string)) {
        return "";
    }

    $string = trim($string);

    $string = mb_strtolower($string, "UTF-8");;

    $string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);

    $string = preg_replace("/[\s-]+/", " ", $string);

    $string = preg_replace("/[\s_]/", $separator, $string);

    return $string;
}
public function store(Request $request)
{
    $this->validate($request, array(
        'title'         => 'required|max:255',
        'slug'          => 'required|min:3|max:255|unique:posts',
        'body'          => 'required',
    ));
    $post = new Post;
    $post->title = $request->input('title');
    $post->slug = $this->slug($request->slug);
    $post->body = $request->input('body');
    $post->save();

    return redirect('admin/posts')->with('success', 'post is successfully saved');
}
    public function update(Request $request, $id)
{
    if ($request->isMethod('get'))
        return view('content.admin.post.index', ['url' => Post::find($id)]);
    else {
        $rules = [
            'title'         => 'required|max:255',
            'slug'          => 'required|min:3|max:255|unique:posts,slug,{$post->slug},slug',
            'body'          => 'required',
            ];
        $this->validate($request, $rules);
        $post = Post::find($id);

        $post->title = $request->title;
        $post->slug = $this->slug($request->slug);
        $post->body = $request->body;

        $post->save();

        return redirect('/admin/posts');
    }
}

【问题讨论】:

    标签: mysql laravel laravel-5 laravel-6 laravel-6.2


    【解决方案1】:

    在 slug 字段上进行转换将其传递给验证器之前。

    public function store(Request $request)
    {
        $request->slug = $this->slug($request->slug);
        $this->validate($request, array(
            'title'         => 'required|max:255',
            'slug'          => 'required|min:3|max:255|unique:posts',
            'body'          => 'required',
        ));
        $post = new Post;
        $post->title = $request->input('title');
        $post->slug = $request->input('slug');
        $post->body = $request->input('body');
        $post->save();
        return redirect('admin/posts')->with('success', 'post is successfully saved');
    }
    

    【讨论】:

      【解决方案2】:

      为什么不在数据库迁移中将 slug 列设置为唯一? 像这样:

      $table->string('slug')->unique();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-27
        • 2011-05-20
        • 2015-08-27
        • 2015-10-23
        • 2019-08-15
        • 2014-05-17
        相关资源
        最近更新 更多