I am using UUIDs in my application and I have implemented the feature as shown online like this:
trait Uuid { protected static function boot(): void { parent::boot(); static::creating(function (Model $model) { if (!$model->getKey()) { $model->{$model->getKeyName()} = (string) Str::uuid(); } }); } public function getIncrementing(): bool { return false; } public function getKeyType(): string { return 'string'; } }
In retrospect, this applies to almost anywhere: I'm trying to create a pivot table on my product like this:
public function categories(): BelongsToMany { return $this->belongsToMany( Category::class, ProductCategory::class, 'product_id', 'category_id' ); }
The migration looks like this:
public function up(): void { Schema::create('product_categories', function (Blueprint $table) { $table->uuid('id')->primary(); $table->foreignUuid('product_id')->index(); $table->foreignUuid('category_id')->index(); $table->timestamps(); }); }
However, whenever I do the following while seeding:
Product::first()->categories()->sync(Categories::all()->pluck('id'));
I see this error:
BothPDOException::("SQLSTATE[HY000]: General error: 1364 Field "id" has no default value")
Category
and ProductCategory
use the Uuidd
trait and I don't know how to make it work.
Thanks for any help.
As one of the possible solutions, you can use your own model and characteristics of the pivot table.
More: https://laravel.com/docs/ 9.x/eloquent-relationships#defining-custom-intermediate-table-models.