内容简介: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(',');
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Yii2的场景(scenario)和验证规则(rule)
- Laravel中unique和exists验证规则的优化详解
- drools规则出现中文验证 与jvm 默认编码(The default charset is determined during virtual-machin
- 神经规则引擎:让符号规则学会变通
- ???? 图解 == 操作符规则和不同类型间转换规则
- Wireshark 【OSI二层】抓包过滤规则和显示过滤规则实例
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
HTTP Essentials
Stephen A. Thomas、Stephen Thomas / Wiley / 2001-03-08 / USD 34.99
The first complete reference guide to the essential Web protocol As applications and services converge and Web technologies not only assume HTTP but require developers to manipulate it, it is be......一起来看看 《HTTP Essentials》 这本书的介绍吧!
CSS 压缩/解压工具
在线压缩/解压 CSS 代码
HSV CMYK 转换工具
HSV CMYK互换工具