One problem at a time.
Problem #1
$synced = $product->categories()->sync([250]);
Your code should work, so have you checked in the database if there are the right values saved in the pivot table ?
I am working on a project in laravel that uses a fair amount of both pivot tables and polymorphic pivot tables. When using the sync() method I am running into a few issues, all related to using extra pivot data. What I’m basically wondering is, is there a different method to use that handles these situations better? Am I doing something wrong here? Is this just the way it is? Do I basically need to write a custom sync method?
Using the sync() method with extra pivot data sometimes updates unnecessarily, polluting the return data, and in other cases it does not update or remove records that weren’t in the provided array.
I have a product with Id 1 and a category with Id 250. The category pivot table has an additional column called 'type'.
We already have this record:
category_id: 250, product_id: 1, type: ‘customer’, (plus created_at and updated_at).
And a relationship:
public function categories() { return $this->belongsToMany(Category::class)->withPivot('type')->withTimestamps(); }
And a model instance in the variable $product:
$product = Product::find(1);
If I do something like this:
$synced = $product->categories()->sync([250]);
$synced will be an array where attached, detached, and updated are all empty arrays. In this case, I would expect that I was sending sync off to make sure that the only relationship between product 1 and any categories is the one record with category 250 and that it would have no extra pivot data, as I didn't include any. However, sync is clearly only caring about the fact that the only category linked up with product 1 is of id 250. I could see this being the intended behavior. If it is, is there a better way to handle this? I want to actually be able to use the return data from sync. If I have to detach everything then sync it every time the return data is useless.
Next up, same scenario except I include pivot data that matches the existing record:
$synced = $product->categories()->sync([250 => ['type' => ‘customer’]]);
This time, $synced now has some data in updated. Instead of being empty, it says it updated the relationship with category 250.
$synced = [ 'attached' => [], 'detached' => [], 'updated' => [0 => 250], ]
It doesn't mention the extra pivot data, which I find odd. Additionally, it has updated the 'updated_at' column in the pivot table even though no other data has changed. The record that was there before already had the type filled in as ‘customer’. I asked it to sync a relationship plus pivot data. All of that already existed in the pivot table. I'd expect the result this time to be empty arrays for attached, detached, and updated.
I removed the last set of problems to move to a separate thread to keep each more focused.
Please or to participate in this conversation.