08 August 2017

How to Setting Laravel UUID in Laravel 5

What is a UUID?

UUID is short for “universal unique identifier” which is a set of 36 characters, containing letters and numbers. Each set should be unique, with there only being a chance for repetition each 100 years, you can read more about it and check out some cool statistics here and here.

The Problem

During this time, we often use Auto-Increment Integer as Primary Key in our database tables. Then usually in the web application, we access the data with a URL address like this:
Http://myapplication.com/user?id=105
Http://myapplication.com/user/105
Users of our application can easily recognize the URL, where our User ID is 105. One time the user is idly accessing the URL and replace the User ID eg 104, or 106. So User can know who the User who signed up before and after himself, whereas It may not be allowed. Or, the user is using User ID = 1, which usually is User ID 1 that is User Administrator, this is dangerous.

What are the benefits?

With distributed systems you can be pretty confident that the PK’s will never collide.
2. When building a large scale application when an auto increment PK is not ideal.
3. It makes replication trivial (as opposed to int’s, which makes it REALLY hard)
4. t doesn’t show the user that you are getting information by id, for example https://example.com/user/13/settings


Solution: What is a UUID (Universally Unique Identifier)?


From Wikipedia:
The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. In this context the word unique should be taken to mean “practically unique” rather than “guaranteed unique”. Since the identifiers have a finite size, it is possible for two differing items to share the same identifier. The identifier size and generation process need to be selected so as to make this sufficiently improbable in practice. Anyone can create a UUID and use it to identify something with reasonable confidence that the same identifier will never be unintentionally created by anyone to identify something else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve identifier (ID) conflicts.
Simply put, UUID is a collection of 32 characters (Strings) created randomly (random) with unique techniques that are guaranteed unique for each data. Within 1 second, if the _-_generate_ 1000 UUID, it is unlikely that the same UUID. So it is more suitable for use as Primary Key.

How to Implement UUID to Laravel

If we search the Composer Package in the popular Packagist library used to create this UUID is ramsey / uuid / website: RAMSEY / UUID / source: GitHub.

Add this package in composer.json with the command:
composer require ramsey/uuid
Then to use it, can use an example like the one in the documentation of this library:
require 'vendor/autoload.php';

use Ramsey\Uuid\Uuid;

// Generate a version 1 (time-based) UUID object
$uuid1 = Uuid::uuid1();
echo $uuid1->toString() . "\n"; // e4eaaaf2-d142-11e1-b3e4-080027620cdd

// Generate a version 3 (name-based and hashed with MD5) UUID object
$uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid3->toString() . "\n"; // 11a38b9a-b3da-360f-9353-a5a725514269

// Generate a version 4 (random) UUID object
$uuid4 = Uuid::uuid4();
echo $uuid4->toString() . "\n"; // 25769c6c-d34d-4bfe-ba98-e0ee856f3e7a
// Generate a version 5 (name-based and hashed with SHA1) UUID object
$uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net');
echo $uuid5->toString() . "\n"; // c4a760a8-dbcf-5254-a0d9-6a4474bd1b62 

Data Database Type

Because we use the UUID string as the Primary Key, the data field type created can not be Integer, but must be Variable Character (VARCHAR), with maximum 32 characters length. In Laravel, for Migration and Schema Builder must also be adjusted:
Schema::create('users', function(Blueprint $table)
{
    $table->string('id', 32)->primary();
});

Eloquent ORM

In order to use the UUID in the Eloquent ORM Model, we must first disable the auto increment feature, by:
class User extends Model {
    protected $table = 'users';
    public $incrementing = false;
}
Then we can use this UUID at the Create / Update data as usual.
use Ramsey\Uuid\Uuid;
class UserController extends Controller {
    public function store()
    {
        $user           = new User;
        $user->id       = Uuid::uuid4()->getHex(); // toString();
        $user->name     = "Yoga Hanggara";
        $user->save();
    }
    public function update($id)
    {
        $user = User::find($id);
        $user->save();
    }
 Thats it, I hope this post can be useful for you. We take from some sources of them

No comments: