How can I generate an unique id in Symfony 4?
Solution 1
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.
Solution 2
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
}
}
}
Comments
-
peace_love almost 2 years
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".