当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel的unique和exists验证规则的优化

Laravel的unique和exists验证规则的优化

2018年01月28日  | 移动技术网IT编程  | 我要评论

9c8846,蒙古族的资料,蓝色粉末

本文是Laravel实战:任务管理系统(一)的扩展阅读

原文链接:http://pilishen.com/posts/Improvements-to-the-Laravel-unique-and-exists-validation-rules

Laravel中通过ValidatesRequests这个trait来验证requests非常的方便,并且在BaseController类中它被自动的引入了。 exitsts()和unique()这两个规则非常的强大和便利。它们在使用的过程中需要对数据库中已有的数据进行验证,通常它们会像下面这样来写:

// exists example
'email' => 'exists:staff,account_id,1'
// unique example
'email' => 'unique:users,email_address,$user->id,id,account_id,1'

上面这种写法的语法很难记,我们几乎每次使用时,都不得不去查询一下文档。但是从 Laravel 的5.3.18版本开始这两个验证规则都可以通过一个新的Rule类来简化。

我们现在可以使用下面这样的熟悉的链式语法来达到相同的效果:

'email' => [
    'required',
    Rule::exists('staff')->where(function ($query) {
        $query->where('account_id', 1);
    }),
],
'email' => [
    'required',
    Rule::unique('users')->ignore($user->id)->where(function ($query) {
        $query->where('account_id', 1);
    })
],

这两个验证规则还都支持下面的链式方法:

  • where
  • whereNot
  • whereNull
  • whereNotNull

unique验证规则除此之外还支持ignore方法,这样在验证的时候可以忽略特定的数据。

好消息是现在仍然完全支持旧的写法,并且新的写法实际上就是通过formatWheres方法在底层将它转换成了旧的写法:

protected function formatWheres()
{
    return collect($this->wheres)->map(function ($where) {
        return $where['column'].','.$where['value'];
    })->implode(',');
}

原文地址链接

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网