Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Last active April 26, 2022 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whoisryosuke/bdd83f4c411ffee6e4f838ca1a11ec68 to your computer and use it in GitHub Desktop.
Save whoisryosuke/bdd83f4c411ffee6e4f838ca1a11ec68 to your computer and use it in GitHub Desktop.
Laravel - Enabling UUID for model (v6 tested) -- uses \Illuminate\Support\Str::uuid

Migrations

Add UUID (or swap bigIncrement) and make sure to set as primary column:

        Schema::create('events', function (Blueprint $table) {
            $table->uuid('id')->primary();

When using the column as a foreign key in a pivot table, create a UUID column and do the same foreign key assignment:

            $table->uuid('organizer_id');
            $table->foreign('organizer_id')->references('id')->on('users')->onDelete('cascade');

Model

  1. Create a trait to add to models:

app/Traits/Uuids.php

<?php
namespace App\Traits;

trait Uuids
{
    /**
     * Boot function from laravel.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->{$model->getKeyName()} = (string) \Illuminate\Support\Str::uuid();
        });
    }
}

Then "use" that trait in your model:

app/Events.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Traits\Uuids;

class Events extends Model
{
    /**
     * Generates and inserts uuid when creating new items
     */
    use Uuids;
}
  1. Cast UUID as string inside model (or you'll get errors from foreign keys failing, or UUIDs cast as tiny integers that resemble classic IDs). Reference

app/YourModel.php

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'string',
    ];

Congrats, you have UUIDs in your app

@christmex
Copy link

christmex commented Apr 26, 2022

Hi mate, thx for this, but can u help me with laravel 9 ? ive tried the same way, and trying to find anytinh on google but still got nothing, i alread make question here if you want to see the detail, [How to use foreignUuid in laravel 9]
thank youu..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment