search

Home  >  Q&A  >  body text

The use of adding data in laravel uses valdiate to verify whether the data exists in the relational table

When adding data, is it possible to verify whether the data exists in the relational table through valdiate?

黄舟黄舟2829 days ago627

reply all(3)I'll reply

  • 某草草

    某草草2017-05-16 16:50:44

    https://laravel.com/docs/5.3/...

    reply
    0
  • 迷茫

    迷茫2017-05-16 16:50:44

    1. You can customize the verification, it seems a bit complicated... My level is limited, you can read the official documents by yourself

    2. You can also think of it as a simple and crude method, write your join table query verification logic in Controller and manually redirect and throw an error if there is an exception, as shown in the following code

        public function store(Request $request)
        {
            $this->validate($request, [
                'password' => 'required|min:6|max:100',
                'newPassword' => 'required|min:6|max:100',
                'newPasswordConfirm' => 'required|same:newPassword|min:6|max:100',
            ], [], [
                'password' => '旧密码',
                'newPassword' => '新密码',
                'newPasswordConfirm' => '确认新密码',
            ]);
    
            #这个地方就是个自定异常的演示, 并不是你要的连表查询, 这里只提供一个思路
            if (!\Hash::check($request->get('password'), \Auth::user()->password)) {
                return redirect()->back()->withErrors(['password' => '旧密码错误']);
            }
    
        }

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 16:50:44

    Yes, use existsrules, such as

    'exists:表名,字段名'
    

    Depending on your situation, using the built-in rules is not enough and you need to create new rules yourself. Here is an example of creating a rule to verify Chinese

    $validator = app('validator');
    $validator->extend('chinese', function($attribute, $value, $parameters, $validator) {
        return Validator::chinese($value);
    });
    $validator->replacer("chinese", function($message, $attribute, $rule, $parameters) {
        if ($message == 'validation.chinese') {
            return "属性 {$attribute} 必须是合法的中文";
        }
    
        return $message;
    });
    

    Refer to the Custom Validation Rules section of the document for details.

    reply
    0
  • Cancelreply