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

原文地址链接


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

查看所有标签

猜你喜欢:

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

Realm of Racket

Realm of Racket

Matthias Felleisen、Conrad Barski M.D.、David Van Horn、Eight Students Northeastern University of / No Starch Press / 2013-6-25 / USD 39.95

Racket is the noble descendant of Lisp, a programming language renowned for its elegance and power. But while Racket retains the functional goodness of Lisp that makes programming purists drool, it wa......一起来看看 《Realm of Racket》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具