Search code examples
laravellaravel-7laravel-validationlaravel-request

How to use the ignore rule in Form Request Validation


this is PostsRequest.php in http/request:

<?php

    namespace App\Http\Requests;
    
    use App\Post;
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Validation\Rule;
    
    class PostsRequest 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','max:255', Rule::unique('posts')->ignore($this->id)],
                'slug' => ['required', Rule::unique('posts')->ignore($this->id),],
                'content' => 'required',
                'type' => 'required|in:blog,download,page',
                'status' => 'required',
            ];
        }
    }

and this is edit() method in PostController.php

   public function update(PostsRequest $request, $id)
    {

        $validated = $request->validated();
        $validated['user_id'] = auth()->user()->id;
        $post = Post::find($id)->fill($validated);
        $post->save();

        return redirect()->action('PostController@index');
    }

Problem: show error in update page that this value is already exists.
who to resolve problem unique fields in edit form?


Solution

  • If you're wanting to resolve the $id from the route then you can use the route() method in your request class e.g.

    Rule::unique('posts')->ignore($this->route('id'))