Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PeterSH's avatar

Laravel: Update pivot table relation

I'm struggling to update a relationship of a pivot table, I have three models, " Product", " Location" and " LocationProduct" defined as below;

class Product extends Model
{
    public function locations(): BelongsToMany
    {
        return $this->belongsToMany(Location::class, 'location_product', 'product_id', 'location_id');
    }

    public function locationProducts(): HasMany
    {
        return $this->hasMany(LocationProduct::class);
    }
}
class Location extends Model
{
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'location_product', 'location_id', 'product_id');
    }

    public function locationProducts(): HasMany
    {
        return $this->hasMany(LocationProduct::class);
    }
}
class LocationProduct extends Pivot
{
    public function location(): BelongsTo
    {
        return $this->belongsTo(Location::class);
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }
}

(some unrelated lines are missing)

So far I've tried:

// locationProduct: existing LocationProduct model
// newLocation: existing Location model other than current related Location model
$locationProduct->location()->associate($newLocation);
$locationProduct->save();

But this throws an "zero-length delimited identifier" SQL exception, I'm guessing because the model doesn't have an ID as primary key.

I've also tried:

// product: related Product model from locationProduct
$product->locations()->updateExistingPivot($locationProduct->id, ['location_id' => $location->id]);

But this will update all products.

Is there any way to update the location relation on the pivot table? If needed I can add the tables structure too.

0 likes
1 reply
kevinbui's avatar

I believe you want to attach a new location to a product. Is there any problem with simply doing this?

$production->locations()->attach($newLocation->id);

Please or to participate in this conversation.