Improvements to the Laravel unique and exists validation rules

Improvements to the Laravel unique and exists validation rules

Validating requests in Laravel is simple with its ValidatesRequests trait that is automatically included through the BaseController.

It’s powerful and provides a lot of useful rules for common use cases. Two rules, exists() and unique(), are used to validate against data stored in your database and they’ve always had a format like this:

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

As you can see, the style of this is not the easiest to remember and it’s something you almost always have to consult the docs on.

Starting with Laravel v5.3.18 both of these rules have been simplified with an introduction of a new Rule class.

Using the same examples above you can now use a familiar fluent syntax to get 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 support the following fluent methods:

  • where
  • whereNot
  • whereNull
  • whereNotNull

The unique rule includes the extra ignore method so you can validate against the rest of your data.

Another bonus with these new features is that the old style is still fully supported and the way it works is by taking these and converting back into the old string style through a formatWheres method:

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

To get the latest version all you need to do is run composer update and once it pulls down 5.3.18 you will be all set to start using this new fluent style.


Filed in: News / Validation


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Web Application Developer
Cleveland, OH
PS Lifestyle
Full-Stack Developer
Tampa, FL / Remote
Nu Image Medical
PHP Developer
Remote
X-Team
Full-Stack Developer
Sioux Falls, SD or Remote
Electric Pulp
Senior PHP / Vue.js Developer
Portland, OR / Remote
Bright Oak
Full Stack Vue.js Developer (Front-end focus)
Remote
LenderHomePage.com
Senior Laravel Web Application Developer
NYC or Remote
Happy Cog