Skip to content

Instantly share code, notes, and snippets.

@grandmanitou
Created September 28, 2019 11:44
Show Gist options
  • Save grandmanitou/4bd5cdde7c2d0a22492af9b2badc8453 to your computer and use it in GitHub Desktop.
Save grandmanitou/4bd5cdde7c2d0a22492af9b2badc8453 to your computer and use it in GitHub Desktop.
Uuid trait for laravel 5.x & 6.x models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Traits\Uuid;
class MyModel extends Model
{
use Uuid;
protected $guarded = [];
}
?>
<?php
namespace App\Models\Traits;
use Illuminate\Support\Str;
trait Uuid
{
protected static function bootUuid()
{
static::creating(function ($model) {
if (!$model->getKey()) {
$model->{$model->getKeyName()} = (string) Str::uuid();
}
});
}
public function getIncrementing()
{
return false;
}
public function getKeyType()
{
return 'string';
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment