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

栏目: PHP · 发布时间: 8年前

内容简介:Laravel的unique和exists验证规则的优化

本文是 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(',');
}

原文地址链接


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Sequential & Parallel

Algorithms Sequential & Parallel

Russ Miller、Laurence Boxer / Charles River Media / 2005-08-03 / USD 59.95

With multi-core processors replacing traditional processors and the movement to multiprocessor workstations and servers, parallel computing has moved from a specialty area to the core of computer scie......一起来看看 《Algorithms Sequential & Parallel》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试