Last active
January 14, 2023 15:57
-
-
Save imjonos/d163d68940a08110dd1fb8ac3fd32c4d to your computer and use it in GitHub Desktop.
LARAVEL UUID AS PRIMARY KEY
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 | |
use Illuminate\Database\Migrations\Migration; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Support\Facades\Schema; | |
use Illuminate\Support\Str; | |
return new class extends Migration | |
{ | |
/** | |
* Run the migrations. | |
* | |
* @return void | |
*/ | |
public function up(): void | |
{ | |
Schema::create('test_uuids', function (Blueprint $table) { | |
$table->uuid('id')->primary(); | |
$table->string('name'); | |
$table->string('city'); | |
$table->timestamps(); | |
}); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down(): void | |
{ | |
Schema::dropIfExists('test_uuids'); | |
} | |
}; |
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 | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Factories\HasFactory; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Database\Eloquent\Relations\HasMany; | |
use Illuminate\Support\Str; | |
/** | |
* @property string $id | |
*/ | |
class TestUuid extends Model | |
{ | |
use HasFactory; | |
protected $keyType = 'string'; | |
public $incrementing = false; | |
protected $casts = [ | |
'id' => 'string' | |
]; | |
protected $fillable = [ | |
'name', | |
'city' | |
]; | |
protected static function boot() | |
{ | |
parent::boot(); | |
static::creating(fn(self $testUuid) => $testUuid->id = Str::uuid()->toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment