如何在表单请求验证中使用忽略规则

How to use the ignore rule in Form Request Validation

这是 http/request 中的 PostsRequest.php:

<?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',
            ];
        }
    }

这是 PostController.php

中的 edit() 方法
   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');
    }

问题: 在更新页面中显示此值已存在的错误。
谁来解决编辑表单中唯一字段的问题?

如果您想从路由中解析 $id,那么您可以在请求中使用 route() 方法 class 例如

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

问题已解决

更改:

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

与:

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