webpatser/laravel-uuid

[Question] To String Magic Method

DanVeira opened this issue · 2 comments

Why do these two work the same way?

$someModel = new SomeModel();
$someModel->uuid = Uuid::generate(4);
$someModel->save();
$someModel = new SomeModel();
$someModel->uuid = Uuid::generate(4)->string;
$someModel->save();

In the first one I'm not specifically getting the string but yet it works exactly the same.
If I do dd(Uuid::generate(4)) and dd(Uuid::generate(4)->string) it prints different things:

Uuid {#327 ▼
  #bytes: b"Å\x17ãÆˤAËùTÜ┴\x17┌¨¢"
  #hex: null
  #string: "8f17c692-d3cf-41d3-9754-9ac117daf9bd"
  #urn: null
  #version: null
  #variant: null
  #node: null
  #time: null
}

"f48abcbb-fbf7-417e-9493-d67ce86055d0"

So clearly they're different, but when I'm inserting into the database it will automatically get the string key.

Why? Please help me understand this.

See this function in the UUID class

    /**
     * Return the UUID
     *
     * @return string
     */
    public function __toString()
    {
        return $this->string;
    }

When you cast a UUID instance to string:

$uuid = (string) UUID::generate();

this would return the text variant and not instance itself.

When you do

$someModel->uuid = Uuid::generate(4);

eloquent does the string cast for you, so the _toString() method is fired and the Uuid::generate(4)->string is supplied.