Created
November 13, 2019 06:36
-
-
Save alexalouit/cc36ad1d49f8c156a59a46f434fe7451 to your computer and use it in GitHub Desktop.
Laravel/Lumen use uuid as id
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
# lumen: | |
$ composer require ramsey/uuid |
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 Illuminate\Support\Str; | |
class ModelUuid extends Model | |
{ | |
/** | |
* Override default id | |
* | |
* @return void | |
*/ | |
public static function boot() | |
{ | |
parent::boot(); | |
self::creating(function ($model) { | |
$model->id = Str::uuid()->toString(); | |
}); | |
} | |
/** | |
* Get the value indicating whether the IDs are incrementing. | |
* | |
* @return bool | |
*/ | |
public function getIncrementing() | |
{ | |
return false; | |
} | |
/** | |
* Get the primary key for the model. | |
* | |
* @return string | |
*/ | |
public function getKeyName() | |
{ | |
return 'id'; | |
} | |
/** | |
* Get the auto-incrementing key type. | |
* | |
* @return string | |
*/ | |
public function getKeyType() | |
{ | |
return 'string'; | |
} | |
} |
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; | |
class Post extends ModelUuid | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment