大连249建站之家免费精品网站自助建设系统平台免费微
首页 >> 技术分享 >>技术干货 >> 249建站之家:Laravel的unique和exists验证规则的优化
详细内容

249建站之家:Laravel的unique和exists验证规则的优化

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

}


联系我们
更多

联系电话:0411-66373325

联系地址:大连市沙河口区富民广场

公司邮箱:2058793689@qq.com

备案信息:Copyright © 2016-2025,www.my249.com,All rights reserved

辽ICP备17015910号-1

seo seo