Skip to content

Instantly share code, notes, and snippets.

@imjonos
Last active January 14, 2023 15:57
Show Gist options
  • Save imjonos/d163d68940a08110dd1fb8ac3fd32c4d to your computer and use it in GitHub Desktop.
Save imjonos/d163d68940a08110dd1fb8ac3fd32c4d to your computer and use it in GitHub Desktop.
LARAVEL UUID AS PRIMARY KEY
<?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');
}
};
<?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