'Laravel Slug Update Record

I want to ignore the slug if value is not changed. I am currently getting this error whenever i update the form.

This is my request on validation.

namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class ProductInsertFormRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; }

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title'=>'required',
        'regularPrice'=>'required',
        'slug'=>'required|alpha_dash|min:5|max:255|unique:products,slug',
    ];
}

}



Solution 1:[1]

to ignore a particular row in database table when checking unique, you need to use unique() rule with ignore() function

'slug' => ['required', 'alpha_dash', 'min:5', 'max:255', Rule::unique('products', 'slug')->ignore($this->product->slug)

This will check unique in 'slug' column of the 'products' table, except this particular row which has 'this slug'

Solution 2:[2]

  1. Ignore() function in Rule is working only with id.
  2. So I changed the code into following:

    public function rules()
    {
    $decrypted = Crypt::decrypt($this->id);
    //$slug = Product::whereId($decrypted)->pluck('slug')->first();
    
    //return dd($slug);
     return [
        'title'=>'required',
        'regularPrice'=>'required',
        'slug' => ['required', 'alpha_dash', 'min:5', 'max:255', Rule::unique('products', 'slug')->ignore($decrypted)]
    ];
     }
    

Solution 3:[3]

The best way you can do this is to use one form request to create and update a record

$postSlug = $this->route()->parameter('slug');
if (in_array($this->method(), ['PUT', 'POST']) && $postSlug) {
    $post = $this->postService->getBySlug($postSlug);
    $rules['slug'] = [
        'required',
        Rule::unique('posts')->ignore($post->id),
    ];
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 JaRoi
Solution 3 morteza