Search code examples
mysqllaravellaravel-5laravel-6laravel-6.2

Laravel Slug Duplicate


when i trying to create post with the same slug it create post normally also in update the same problem in this case i'v duplicate slugs for post

i search a lot about this problem but i didn't get any answers

any idea to solve this problem ?

Model

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

Controller

    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');
    }
}

Solution

  • Preform your transformations on the slug field before passing it to the validator.

    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');
    }