【问题标题】:Where should the logic for complex update validation live?复杂更新验证的逻辑应该放在哪里?
【发布时间】:2019-12-16 17:20:04
【问题描述】:

我正在与我的团队讨论并使用 Laravel 框架。

验证对作为关系的现有模型属性的更新需要几次数据库调用以确保它符合约束条件。

我的第一个想法是创建一个自定义验证器,但是,这需要在验证器中进行查询。一种是让模型被更新,一种是获得存在的关系,另一种是获得它也将被更新的关系。这个验证器也只会用于更新这个模型上的这个属性。

或者,这可以通过事件进行验证,但我不确定保留该验证逻辑的最佳位置。

任何建议将不胜感激。

【问题讨论】:

    标签: laravel laravel-5 model-view-controller crud


    【解决方案1】:

    Laravel 的自定义验证规则几乎就是为此而制定的

    use Illuminate\Validation\Rule;
    
    Validator::make($data, [
        'email' => [
            'required',
            Rule::exists('staff')->where(function ($query) {
                $query->where('account_id', 1);
            }),
        ],
    ]);
    

    您可以在查询中添加任何您想要的约束,只要返回至少 1 条记录,它就会通过

    【讨论】:

    • 但是在特定的用例中只使用一次就感觉很奇怪
    • 这就是验证规则的用途,其中大多数不适用于一两个以上的请求
    • 而忽略多次查询数据的开销?
    • 如果这就是验证数据所需要的,还有什么方法可以解决这个问题?您要执行哪种验证?是否有必要让所有三个原始模型、旧关系和新关系来执行验证,或者您可以只比较关系对象吗?
    • 比较每个事物的状态和其他一些事物。我可以将查询简化为一个不加水合的原始查询,以节省一些开销,甚至可能是一个短暂的缓存。
    【解决方案2】:

    编辑表单验证放置命名空间 App\Http\Requests\Post;

    namespace App\Http\Requests\Post;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class EditFormValidation 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:150 | unique:posts,title,'.$this->request->get('id'),
                'description' => 'required'
            ];
        }
    
        public function messages()
        {
            return [
                'title.required' => 'This filed is required.',
            ];
        }
    }
    

    然后在控制器中

    public function update(EditFormValidation $request)
        {
            $row = Post::find($request->get('id'));
            $row->update([
                'title' => $request->get('title'),
                'slug' => str_slug($request->get('title')),
                'description' => $request->get('description'),
                'status' => $request->get('status')
            ]);
    
            $request->session()->flash('success_message', 'Post successfully updated.');
            return redirect()->to('post');
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 2016-12-18
      • 2012-07-16
      • 1970-01-01
      相关资源
      最近更新 更多