dmytroshved's avatar

Laravel: UUID Trait

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:

I tried to use this code, it works, but I am not sure if this trait will override the boot() methods from other traits?

Would be grateful for your help

Best regards

0 likes
3 replies
dmytroshved's avatar
dmytroshved
OP
Best Answer
Level 6

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',
    ];

   //...
}

so it's not necessary to use any custom traits.

martinbean's avatar

@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.

1 like
Tray2's avatar

I would suggest sticking to regular integers as your id, it will be way faster, and indexable.

1 like

Please or to participate in this conversation.