search

Home  >  Q&A  >  body text

General error in Laravel 9.x: Field 'id' has no default value

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:

PDOException::("SQLSTATE[HY000]: General error: 1364 Field "id" has no default value")

Both

Category and ProductCategory use the Uuidd trait and I don't know how to make it work.

Thanks for any help.

P粉714780768P粉714780768267 days ago547

reply all(1)I'll reply

  • P粉731977554

    P粉7319775542024-04-07 09:44:23

    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.

    reply
    0
  • Cancelreply