Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Created July 5, 2018 17:36
Show Gist options
  • Save calebporzio/f3cbd3222cb5029c0df30f72c4dc08c9 to your computer and use it in GitHub Desktop.
Save calebporzio/f3cbd3222cb5029c0df30f72c4dc08c9 to your computer and use it in GitHub Desktop.
A little trait to add to models that will have Uuids
<?php
// Example usage in a model:
class ExampleModel extends Model
{
use HasUuid;
protected $primaryKey = 'uuid';
public $incrementing = false;
}
// The Trait:
trait HasUuid
{
public static function bootHasUuid()
{
static::creating(function ($model) {
if (! $model->{$model->getKeyName()}) {
$model->{$model->getKeyName()} = static::generateUuid();
}
});
}
public static function generateUuid()
{
return (string) Illuminate\Support\Str::uuid();
}
}
@ed-fruty
Copy link

ed-fruty commented Jul 11, 2018

Also you need to specify key type and incrementing. And you can do it in trait, like:

trait HasUuid
{
    public static function bootHasUuid()
    {
        $callback = function (Model $model) {
            $model->setKeyType('string');
            $model->setIncrementing(false);
        
            if (! $model->getKey()) {
                $model->{$model->getKeyName()} = static::nextIdentity();
            }
        };

        static::creating($callback);
        static::retrieved($callback);
    }

    public static function nextIdentity()
    {
        return Illuminate\Support\Str::uuid()->toString();
    }
}

@whoisryosuke
Copy link

Didn't work for me. Ended up using:

<?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();
        });
    }
}

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