Skip to content

Instantly share code, notes, and snippets.

@bayareawebpro
Last active September 24, 2019 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayareawebpro/ca72ad4110c2e519ff09171677fd0bef to your computer and use it in GitHub Desktop.
Save bayareawebpro/ca72ad4110c2e519ff09171677fd0bef to your computer and use it in GitHub Desktop.
<?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