This time to bring you laravel in the unique and exists validation rules optimization steps in detail, laravel in the unique and exists validation rules optimization of the considerations are, the following is the actual case, together to see.
Objective
Laravel provides several ways to validate the application input data. By default, the Laravel controller base class uses validatesrequests trait, which provides a convenient way to validate incoming HTTP requests through various powerful validation rules.
It is very convenient to verify requests by validatesrequests this trait in laravel, and it is automatically introduced in the Basecontroller class. The two rules of Exitsts () and unique () are very powerful and convenient.
They need to validate the data that is already in the database as they are used, and usually they write as follows:
exists example ' email ' = ' exists:staff,account_id,1 '//Unique example ' email ' = ' unique:users,email_address,$ ' user->id,id,account_id,1 '
The syntax of this notation is hard to remember, and we have to check the documentation almost every time we use it. But starting with the version of Laravel 5.3.18 These two validation rules can be simplified by a new rule class.
We can now use the familiar chained syntax below 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); })],
Both of these validation rules also support the following chained methods:
where
Wherenot
Wherenull
Wherenotnull
The unique validation rule also supports the Ignore method so that specific data can be ignored when validating.
The good news is that the old notation is still fully supported, and the new writing is actually converting it to the old way at the bottom through the Formatwheres method:
protected function Formatwheres () {return collect ($this->wheres)->map (function ($where) {return $where [' column ' ]. ', '. $where [' value ']; })->implode (', ');}
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP bidirectional list using the detailed
PHP using the foreach Transform array steps