How can I generate an unique id in Symfony 4?

peace_love picture peace_love · Nov 27, 2018 · Viewed 12.3k times · Source

I want to create a unique id, so in my Controller.php, I write this:

use Symfony\Component\Validator\Constraints\Uuid;

and later in my function:

$unique_id = $this->uuid = Uuid::uuid4();

But I get the error message:

Attempted to call an undefined method named "uuid4" of class "Symfony\Component\Validator\Constraints\Uuid".

Answer

wanna know picture wanna know · Nov 27, 2018

You can use ramsey/uuid from https://packagist.org/packages/ramsey/uuid

composer require ramsey/uuid

After the installation :

use Ramsey\Uuid\Uuid;

function generateUid()
{
   return Uuid::uuid4();
}

You can check the documentation for more informations.