这次给大家带来laravel中unique和exists验证规则优化步骤详解,laravel中unique和exists验证规则优化的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
laravel提供了多种方法来验证应用输入数据。默认情况下,laravel的控制器基类使用validatesrequests trait,该trait提供了便利的方法通过各种功能强大的验证规则来验证输入的http请求。
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(',');
}
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
php双向链表使用详解
php运用foreach转换数组步骤详解
以上就是laravel中unique和exists验证规则优化步骤详解的详细内容。