Laravel unique and exists validation rule optimization, laravelunique

Source: Internet
Author: User

Laravel unique and exists validation rule optimization, laravelunique

This article is about Laravel practice: task management system (I) Extension reading

Link: http://pilishen.com/posts/Improvements-to-the-Laravel-unique-and-exists-validation-rules

In Laravel, the trait of ValidatesRequests is used to verify the convenience of requests, and it is automatically introduced in the BaseController class. Exitsts () and unique () rules are very powerful and convenient. They need to verify the existing data in the database in the Process of use, usually they will write like below:

// exists example'email' => 'exists:staff,account_id,1'// unique example'email' => 'unique:users,email_address,$user->id,id,account_id,1'

The above syntax is hard to remember. We have to query the document almost every time we use it. However, since Laravel 5.3.18, both verification rules can be simplified through a new Rule class.

Now we can use the following familiar chain syntax to achieve the same effect:

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

The two verification rules also support the following chained method:

  • Where
  • WhereNot
  • WhereNull
  • WhereNotNull

The unique verification rules also support the ignore method, so that specific data can be ignored during verification.

The good news is that the old writing method is still fully supported, and the new writing method is actually converting it into the old writing method at the underlying layer through the formatWheres method:

protected function formatWheres(){    return collect($this->wheres)->map(function ($where) {        return $where['column'].','.$where['value'];    })->implode(',');}

Original address link

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.