Optimized Explanation of unique and exists Verification Rules in Laravel

  • 2021-09-11 19:36:04
  • OfStack

Preface

Laravel provides a variety of methods to validate application input data. By default, Laravel's controller base class uses ValidatesRequests trait, which provides a convenient way to validate incoming HTTP requests with a variety of powerful validation rules.

In Laravel, it is very convenient to verify requests by ValidatesRequests, which is trait, and it is automatically introduced in BaseController class. The exitsts () and unique () rules are very powerful and convenient.

When they are used, they need to verify the existing data in the database. Usually, they will be written as follows:


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

The grammar of the above writing is difficult to remember, and we have to query 1 document almost every time we use it. But starting with version 5.3. 18 of Laravel, both validation rules can be simplified with a new Rule class.

We can now 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);
 })
],

Both 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 during validation.

The good news is that the old writing is still fully supported, and the new writing is actually converted to the old writing at the bottom through the formatWheres method:


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

Summarize


Related articles: