Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
UUID Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
// Abstract class using inheritance rather than composition to avoid trait override errors
abstract class UuidModel extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
static::creating(function (Model $model) {
$model->{$model->getKeyName()} = Uuid::uuid4()->toString();
});
}
public function resolveRouteBinding($value)
{
// Postgres will throw if you use a non-UUID in a WHERE for a UUID column. This
// short-circuits that process and returns empty before we hit the database
// because we know we won't get anything anyway.
return Uuid::isValid($value) ? parent::resolveRouteBinding($value) : null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.