Skip to content

Commit

Permalink
Add default UUID on create and save event
Browse files Browse the repository at this point in the history
  • Loading branch information
KFoobar committed Feb 7, 2022
1 parent 8b9c8db commit fff78ef
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 11 deletions.
9 changes: 6 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "kfoobar/laravel-uuid",
"description": "Eloquent UUID trait for Laravel",
"type": "plugin",
"license": "MIT",
"authors": [
{
Expand All @@ -9,13 +10,15 @@
}
],
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": ">=7.3",
"illuminate/support": "^5.5|^6|^7|^8|^9"
"php": "^7.3|^8.0",
"illuminate/database": ">=5.5",
"illuminate/support": ">=5.5"
},
"autoload": {
"psr-4": {
"KFoobar\\LaravelUuid\\": "src/KFoobar/LaravelUuid/"
"KFoobar\\Uuid\\": "src/"
}
}
}
8 changes: 0 additions & 8 deletions src/LaravelUuid/Traits/HasUuid.php

This file was deleted.

34 changes: 34 additions & 0 deletions src/Traits/HasUuid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace KFoobar\Uuid\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

trait HasUuid
{
/**
* Bootstrap the model and its traits.
*
* @return void
*/
protected static function boot()
{
parent::boot();

static::creating(function (Model $model) {
$model->addDefaultUuid($model);
});

static::saving(function (Model $model) {
$model->addDefaultUuid($model);
});
}

protected function addDefaultUuid(Model $model)
{
if (empty($model->uuid)) {
$model->uuid = Str::uuid()->toString();
}
}
}

0 comments on commit fff78ef

Please sign in to comment.