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

Senior Software Engineer - LAMP/PHP/MySQL/Laravel
Los Angeles / Remote
Ranker
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
In-house Laravel Developer.
Gold Coast / Australia
MXstore
Laravel Developer
Oak Brook, IL
Tidal Commerce
Senior Backend Engineer
Santa Monica only
Saatchi Art
Senior Laravel Developer
San Francisco
Stitch Labs
Senior Software Developer
South Jordan, UT
Lendio