Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 805
peace_love Avatar asked Nov 27 '18 13:11

peace_love


2 Answers

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.

like image 75
wanna know Avatar answered Oct 26 '22 23:10

wanna know


Only doctrine can automatically generate uuid for you when persisting objects to database. You can set it up like this in your entity.

/**
 *
 * @ORM\Id
 * @ORM\Column(name="id", type="guid")
 * @ORM\GeneratedValue(strategy="UUID")
 */
protected $id;

And this exactly is a problem sometimes, when you need the uuid immediately for further instructions in your code, but you could not persist the object at that point of time. So I made good experiences using this package:

https://packagist.org/packages/ramsey/uuid

<?php

namespace YourBundle\Controller;

use Ramsey\Uuid\Uuid;

/**
 * Your controller.
 *
 * @Route("/whatever")
 */
class YourController extends Controller
{
    /**
     * @Route("/your/route", name="your_route")
     */
    public function yourFunction(Request $request)
    {
        try {
            $uuidGenerator = Uuid::uuid4();
            $uuid = $uuidGenerator->toString();
        } catch (\Exception $exception) {
            // Do something
        }
    }
}
like image 39
Chris P. Bacon Avatar answered Oct 27 '22 01:10

Chris P. Bacon