Skip to content

Instantly share code, notes, and snippets.

@iansltx
Created August 1, 2019 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iansltx/0d00d9cc26e20b80b8d8dd0a65b03c8b to your computer and use it in GitHub Desktop.
Save iansltx/0d00d9cc26e20b80b8d8dd0a65b03c8b to your computer and use it in GitHub Desktop.
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