This trait his heavily inspired by and based on the following implementations of UUID generation traits:
- Laravel-UUID: https://github.com/binarycabin/laravel-uuid
- UuidModel Trait: https://gist.github.com/danb-humaan/b385ef92ed2336fd5d12
- The mysterious “Ordered UUID” by Italo Baeza Cabrera: https://itnext.io/laravel-the-mysterious-ordered-uuid-29e7500b4f8
The purpose of this trait is to add a lightweight easy way to make use of UUIDs in Laravel applications without the need to manually specify their creation or search. Features include:
- Automagically generates UUIDs for models when they are being created
- In development and testing environments it will create semi-readable UUID's; prefixing the UUID with the model's name. This can be useful when evaluating raw model data or URLs that feature multiple UUIDs from different models.
- Can be set to create "time ordered" UUIDs, which provides a similar benefit to incrementing integer IDs without the security/ambiguity risk
Add the hasUuid trait to your model:
use HasUuid;
By default, UUIDs will automatically be generated for any model that has a field called 'uuid'
.
To use a custom field name is different, you need to specify the following property:
/**
* Custom UUID field name
*
* @var string
*/
protected uuidFieldName = 'uuid_fieldname';
To use a UUID as a primary key, make sure the model has the following properties specified:
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The primary key's datatype.
*
* @var string
*/
protected $keyType = 'string';
/**
* The ID field is a UUID
*
* @var bool
*/
protected bool $primaryKeyIsUuid = true;
- On PostgreSQL databases, this trait can throw errors in non-production environments as PostgreSQL doesn't support underscores in it's UUID column type. As a workaround/fix, it was replaced with the dash (on line 80). However this resolution has not been fully tested yet.
@LiamKarlMitchell @alexrafuse Nicely spotted guys, thanks for your input and feedback.
Finally got a chance to look into the problem and (long story short), I've realised that when you define uuid as the column type in migrations, Laravel creates a CHAR field for MySQL (which is why it accepts anything), but a an actual UUID column type for PostgreSQL - and that appears to store its UUIDs as bigInt. This being the case (and model names including more letters than hexadecimal has) it gives out a bigInt error when trying to write it as a string.
My current idea is to try and generate a predictable hex prefix that can be used in a similar way to the model name prefix currently working on MySQL but the alternative solutions I've tried so far don't work yet. Will update again when I have something but will probably add a property in the next day or so to just disable the custom uuid in the meantime.
Thanks again for the feedback