Hey everyone, I'm not really sure about this UUID Trait
I found it on some post about How To Use UUID in Laravel, and auhtor provides that code to enable UUID in model instead of basic id:
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait UUID
{
protected static function boot ()
{
// Boot other traits on the Model
parent::boot();
/**
* Listen for the creating event on the user model.
* Sets the 'id' to a UUID using Str::uuid() on the instance being created
*/
static::creating(function ($model) {
if ($model->getKey() === null) {
$model->setAttribute($model->getKeyName(), Str::uuid()->toString());
}
});
}
// Tells the database not to auto-increment this field
public function getIncrementing ()
{
return false;
}
// Helps the application specify the field type in the database
public function getKeyType ()
{
return 'string';
}
}
I tried to use this code, it works, but I am not sure if this trait will override the boot() methods from other traits?
After some research I found that there is actually a better solution from laravel
Laravel provides the HasUuids trait in the version 9.30:
use Illuminate\Database\Eloquent\Concerns\HasUuids;
class User extends Authenticatable
{
use HasUuids;
protected $fillable = [
'email',
'password',
];
//...
}
@dmytro_shved Laravel does have its own HasUuids trait out of the box, but it also assumes you want to use UUIDs for your models’ primary keys. I therefore wrap Laravel’s trait in my own, to also instruct it to store UUIDs in a dedicated uuid instead:
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Concerns\HasVersion4Uuids;
trait HasUuid
{
use HasVersion4Uuids;
public function uniqueIds(): array
{
return [
'uuid',
];
}
}
I can then use this trait to my models instead:
use App\Models\Concerns\HasUuid;
class Channel extends Model
{
use HasUuid;
}
This means my models can still have auto-incrementing integer primary keys (and foreign keys), but also a second UUID identifier for use in URLs etc.