Skip to content

Instantly share code, notes, and snippets.

@umutyerebakmaz
Created November 10, 2021 19:20
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 umutyerebakmaz/dcc6866c383e0bceb25a32dfff526d51 to your computer and use it in GitHub Desktop.
Save umutyerebakmaz/dcc6866c383e0bceb25a32dfff526d51 to your computer and use it in GitHub Desktop.
Laravel 8 - PostgreSQL - UUID Trait Fully Worked
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
class CreateProductsTable extends Migration
{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->uuid('id')->primary()->default(DB::raw('uuid_generate_v4()'));
$table->uuid('brand_id');
$table->longText('title');
$table->string('slug')->unique();
$table->longText('description');
$table->decimal('price');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('products');
}
}
<?php
namespace App\Models;
use App\Traits\Uuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Product extends Model
{
use HasFactory, Uuid;
protected $fillable = [
'title',
'slug',
'description',
'price',
'brand_id',
'discount_id'
];
protected $casts = [
'id' => 'string'
];
protected $primaryKey = 'id';
public $incrementing = false;
public function insects(): BelongsToMany
{
return $this->belongsToMany(Insect::class);
}
}
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait Uuid
{
/**
* Boot function from Laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
}
});
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return false;
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
return 'string';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment