lucadello91/eloquent-uuid

Laravel Eloquent Model trait for using UUID on primary key

1.5.0 2023-09-18 14:28 UTC

This package is auto-updated.

Last update: 2024-10-18 17:28:40 UTC


README

Eloquent UUID

An Eloquent UUID Trait to use with Laravel > 5.6

Latest Version on Packagist Tests Check & fix styling CodeFactor StyleCI MIT licensed Total Downloads

Installation

composer require lucadello91/eloquent-uuid

In your models

For using uuid in your Eloquent Model, just put use UuidModelTrait;:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Lucadello91\EloquentUuid\UuidModelTrait;

class User extends Model
{
    use UuidModelTrait;
}

This package will use UUID v4 values by default. You can use uuid1, uuid3, uuid4, uuid5 or ordered by setting the protected property $uuidVersion in your Eloquent Model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Lucadello91\EloquentUuid\UuidModelTrait;

class Post extends Model
{
    use UuidModelTrait;

    protected $uuidVersion = 'uuid5';
}

Database Schema

When using UuidModelTrait, you have to use uuid your schema :

Schema::create('users', function (Blueprint $table) {
    $table->uuid('id')->primary();
    //...
});

Binary Uuid

If you prefer to use a binary UUID in your database, you just need to cast your primary key to uuid

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Lucadello91\EloquentUuid\UuidModelTrait;

class User extends Model
{
    use UuidModelTrait;
    
    protected $keyType = 'uuid';
    
    //or
    
    protected $casts = [
        'id' => 'uuid',
    ];
}

Running tests

To run the tests, just run composer install and ./vendor/bin/phpunit.

Changelog

Please see CHANGELOG for more information what has changed recently.

Credits

License

The MIT License (MIT). Please see License File for more information.