Created
August 1, 2019 20:49
-
-
Save iansltx/0d00d9cc26e20b80b8d8dd0a65b03c8b to your computer and use it in GitHub Desktop.
UUID Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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