Yevgeniy Zholkevskiy
Contributed by Yevgeniy Zholkevskiy in #26555

In Symfony 4.3, the Validator component added a new constraint called Unique to validate that the elements of a collection are unique (none of them is present more than once):

1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/Person.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    /**
     * @Assert\Unique(message="The {{ value }} email is repeated.")
     */
    protected $contactEmails;
}

The new constraint can be applied to any property of type array or \Traversable and the comparison is strict, so different types are considered different elements (e.g. '7' (string) is different than 7 (integer)).

Symfony already provides some validators related to collections and uniqueness, so keep in mind that:

  • Collection: applies different validation constraints for each collection element.
  • Unique: validates that all the elements of a collection are unique.
  • UniqueEntity: validates that the given property value is unique among all entities of the same type (e.g. the registration email is unique for all the application users).
Published in #Living on the edge