Search code examples
symfonyuuidunique-id

How can I generate an unique id in Symfony 4?


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".


Solution

  • 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.