Check if name is unique among non-deleted items with laravel validation

后端 未结 5 774
走了就别回头了
走了就别回头了 2020-12-05 14:06

I have a simple form which posts to a controller which checks if a name for an item is already taken for a particular project. If it is, then it returns an error. This is th

5条回答
  •  醉话见心
    2020-12-05 14:29

    If someone is looking for solution using Rule class.

    use Illuminate\Validation\Rule;
    
    class UpdateArticleRequest 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()
        {
            $data = $this->request->all();
    
            return [
                'slug' => [
                    'required',                
                    Rule::unique('articles')->ignore($data['id'])->whereNull('deleted_at')
                ]
            ];
        }
    }
    

    Basically, we just ignoring rows which deleted_at fields are not null.

    Here are the methods which you can use along with ignore function: https://laravel.com/api/5.7/Illuminate/Validation/Rules/DatabaseRule.html

提交回复
热议问题