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