0

Environment:PHP, MariaDB, Eloquent

I can insert a uuid into a table easily, with sql query:

INSERT INTO `customer_loginToken` (`customer_id`, `loginToken`, `loginIP`) VALUES (1, uuid(), '127.0.0.1')

But how can I insert a uuid for the column 'loginToken' with the framework Eloquent?

Customer_loginToken::firstOrCreate(   
    array(   
         'customer_id' => $customer[0]->id_kunde,  
         'loginToken' => **'UUID()'**,  
         'loginIP' => $loginIP  
         )  
);  
weirdpanda
  • 2,521
  • 1
  • 20
  • 31
Ying Style
  • 752
  • 2
  • 7
  • 25

1 Answers1

1

It's acutally pretty simple. Say you want to use GUIDs for you UUID, you can do so by the com_create_guid function.

Personally, I prefer the following shim for it as it adds the functionality if the PHP installation lacks it. It's somewhat the same. Also, GUID() is better than com_create_guid().

Another thing to note here is that MySQL describes THIS as format. I am guessing that MySQL's UUID is nothing but a GUID.

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

// Source http://php.net/manual/en/function.com-create-guid.php

Then

Customer_loginToken::firstOrCreate(   
array(   
     'customer_id' => $customer[0]->id_kunde,  
     'loginToken' => GUID(),  
     'loginIP' => $loginIP  
     )  
);

That should do it.

Another thing you can do, if you want to use the number format of the UUID: use the uniqid function. Exact same code, but the GUID() part is changed to uniqid().

If nothing helps, you can write a function and put the value there.

However, remember that you won't be able to exact same value as MySQL as it's a completely random number.

weirdpanda
  • 2,521
  • 1
  • 20
  • 31