General error in Laravel 9.x: Field 'id' has no default value
P粉714780768
P粉714780768 2024-04-06 11:12:54
0
1
521

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粉714780768
P粉714780768

reply all(1)
P粉731977554

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template