This article mainly introduces to you about the unique and exists validation rules in the laravel of the relevant data, the text through the sample code introduced in very detailed, to everyone's study or work has a certain reference learning value, the need for friends below with the small series to learn together.
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 (', ');}
Related recommendations:
Php method for determining IP addresses as valid IP address PHP instance
PHP implementation of AES encryption class definition and usage example PHP tips
PHP implements PHP tips for preventing cross-site and XSS attack code