Today we will learn about how to generate UUIDs with or without third party package. I will share best practise to implement UUIDs. For new beginner learner who have no idea about UUID, we will explain from scratch so you don't have to concern about this topic.
In term UUID in short form of Universal Unique Identifier or Globally Unique Identifier is 128 bits label use for information in computer system. This UUID is usually use as identified in each record row in table.
UUID format look like this
eb38e844-a5c9-11ed-afa1-0242ac120002
The number is base 16 number system (hexadecimal) which is display in separated by hyphens in five groups.
As a unique random value which mean secure as they can't be guess the ID. You may generate a UUID and use it to identify anything, such as a database row, with surly will not appear in another row in your system or anybody else's.
Please take a look below examples to generate UUID.
We have options to generate ordered UUID with first sequence group which is identify as timestamp in hexadecimal. The method will use to ordered is orderedUuid()
. The following sample is shown both options.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class HomeController extends Controller
{
public function uid()
{
// Random value all sequences group
$uuid = Str::uuid();
echo $uuid."<br>";
// The result with order first sequence group
$order1 = Str::orderedUuid();
echo $order1."<br>";
$order2 = Str::orderedUuid();
echo $order2."<br>";
}
}
Output:
587246ec-7f87-4a4a-960a-f11603b0db7f
98666763-c84f-485d-8163-addf017f1acb
98666763-c866-4215-afcc-55df55b04a17
We also can use 3rd party liabrary to generate UUIDs, we will use composer package for generate uuid in Laravel. After installing you don't have to insert alias name in provider. With below command to generate UUID.
Install Packagte webpatser/laravel-uuid composer package to your laravel project by following command:
composer require webpatser/laravel-uuid
After then we can try to generate UUID if it works.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function index()
{
$uuid = Uuid::generate()->string
dd($uuid);
}
}
Output:
e3865264-96a5-45d3-860a-267b7c9d3685
Hope this gonna help you in somedays, please keep enjoyed coding. Thanks have a nice days
You might also like...
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him