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.
Postgresql does not like the custom uuid for testing purposes.
Invalid text representation: 7 ERROR: invalid input syntax for type uuid: "user_7c7-f5eb-4221-ac49-6c9d84a73c98"
It does not follow the format and is invalid UUID v4 for example, seems to work otherwise after removing that part.