【问题标题】:Validation check (if 1 equal to some value from database) Laravel 5验证检查(如果 1 等于数据库中的某个值) Laravel 5
【发布时间】:2015-05-24 20:08:10
【问题描述】:

Laravel 5 中是否有任何方法可以检查某个值是否与数据库中的值相等?

这是我尝试做的:我有表users,在表用户中我有额外的列admin_id。在验证中,我需要检查 admin_id 表单数据库是否等于 1

这是我当前的代码:

  $inputs = array(
        'projects' => Input::get('project'),
        'users'    => Input::get('workers')

    );

    $rules = array(
        'projects' => 'required',
        'users'    => 'required'
    );

    $validator = Validator::make($inputs,$rules);
    if($validator->fails()){
        return false;            
       }else{
        return true; 
    }

【问题讨论】:

    标签: php mysql laravel-5


    【解决方案1】:

    我不知道这里的users 输入是什么——是来自users 表吗?如果是,您可以通过这种方式创建规则:

    $rules = array(
            'projects' => 'required',
            'users'    => ['required', 'exists:users,id,admin_id,1']
        );
    

    所以现在将验证users 是否与users 表中的user_id 匹配,其中admin_id 等于1

    您还应该考虑使用Laravel 5 Requests 对象来验证输入。它比将代码放在 Controller/Model/Repository 中要干净得多。 More about Requst Validation.

    【讨论】:

    【解决方案2】:
        $rules = array(
            'projects' => 'required',
            'users' => [
                'required',
                Rule::exists('users', 'id')->where(function ($query) {
                    $query->where('admin_id', 1);
                }),
            ],
        );
    

    或者如果 admin_id 是动态的,那么使用:

        $variable = 1;
        $rules = array(
            'projects' => 'required',
            'users' => [
                'required',
                Rule::exists('users', 'id')->where(function ($query) use ($variable) {
                    $query->where('admin_id', $variable);
                }),
            ],
        );
    

    【讨论】:

      【解决方案3】:

      $rules = array( 'users' => 'exists:users,admin_id' ); 其中用户表名。可以看到你也想使用用户作为表单字段名称

      【讨论】:

        猜你喜欢
        • 2015-05-25
        • 2016-12-09
        • 2015-08-13
        • 2016-04-22
        • 2019-02-22
        • 1970-01-01
        • 1970-01-01
        • 2018-05-30
        • 2021-12-19
        相关资源
        最近更新 更多