Last active
September 24, 2019 05:49
-
-
Save bayareawebpro/ca72ad4110c2e519ff09171677fd0bef to your computer and use it in GitHub Desktop.
This file contains 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 declare(strict_types=1); | |
namespace App\Traits; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Str; | |
trait UniversallyUnique{ | |
/** | |
* Set Incrementing | |
* (Add UUID Key Type to Migration) | |
* $table->uuid('id')->primary(); | |
* @return bool | |
*/ | |
public function getIncrementing() | |
{ | |
return false; | |
} | |
/** | |
* Get the Key Type | |
* @return string | |
*/ | |
public function getKeyType() | |
{ | |
return 'string'; | |
} | |
/** | |
* Initialize Identifiable Trait | |
* (after boot events registered) | |
* @return void | |
*/ | |
public function initializeIdentifiable(){ | |
//$this->makeUniversallyUnique(); | |
} | |
/** | |
* Make Universally Unique | |
* @return void | |
*/ | |
public function makeUniversallyUnique(){ | |
if(empty($this->getAttribute($this->getKeyName()))){ | |
$this->setAttribute($this->getKeyName(), (string) Str::uuid()); | |
} | |
} | |
/** | |
* Boot the Trait | |
* @return void | |
*/ | |
public static function bootIdentifiable(){ | |
static::creating(function(Model $model){ | |
if(method_exists($model, 'makeUniversallyUnique')){ | |
$model->makeUniversallyUnique(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment