Created
September 28, 2019 11:44
-
-
Save grandmanitou/4bd5cdde7c2d0a22492af9b2badc8453 to your computer and use it in GitHub Desktop.
Uuid trait for laravel 5.x & 6.x models
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 App\Models\Traits\Uuid; | |
class MyModel extends Model | |
{ | |
use Uuid; | |
protected $guarded = []; | |
} | |
?> |
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\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