Home > Mobile >  General error: 1364 Field 'id' doesn't have a default value in Laravel 9.x
General error: 1364 Field 'id' doesn't have a default value in Laravel 9.x

Time:05-08

I am using UUID's across my application and I have implemented the trait, as seen online, like so:

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';
    }
}

Retrospectively, this works almost everywhere: I'm trying to create a pivot table on my products like so:

public function categories(): BelongsToMany
{
    return $this->belongsToMany(
        Category::class,
        ProductCategory::class,
        'product_id',
        'category_id'
    );
}

The migration looks as follows:

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 in my seeding:

Product::first()->categories()->sync(Categories::all()->pluck('id'));

I see this error:

PDOException::("SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value")

Both Category and ProductCategory use the Uuidd trait and I cannot figure out how to make this work.

Any help appreciated.

CodePudding user response:

As one of the possible solutions you could use your own model with your trait for the pivot table.

More: https://laravel.com/docs/9.x/eloquent-relationships#defining-custom-intermediate-table-models.

  • Related