1

In Laravel 4.2, I have the following code:

    $thingIds = [];
    foreach ($this->things as $thing) {
        $thingIds[] = $thing->id;
    }
    $thong->things()->sync($thingIds);
    $thong->save();

Which seems to work for me, however in my pivot table I have an order column that isnt being updated/synced correctly. The order is set to 1 for each item in the pivot table, however I want the order to be representative of the order of the ids in $thingIds.

Is this possible?

Is it possible to update an additional column in the pivot table using ->sync()?


After the suggestion in the comments, I have also tried the following code:

    $thingIds = [];
    foreach ($this->things as $index => $thing) {
        $thingIds[$thing->id] = ['order' => $index];
    }
    $thong->things()->sync($thingIds);
    $thong->save();

And I have tried

    $thingIds = [];
    $order = [];
    foreach ($this->things as $index => $thing) {
        $thingIds[] = $thing->id;
        $order[] = ['order' => $index];
    }
    $thong->things()->sync(array_combine($thingIds, $order));
    $thong->save();

But neither of these is working (the order is still 1 for each item in the pivot table). Can anyone explain what I am doing wrong?


If I do the attaching one at a time, like so:

    foreach ($this->things as $index => $thing) {
        $thong->things()->attach($thing, ['order' => $index]);
    }

The order comes out correctly in the pivot table. How can I get the same effect but whilst still using ->sync()?

Jimmery
  • 9,783
  • 25
  • 83
  • 157
  • Possible duplicate of [Laravel, sync() - how to sync an array and also pass additional pivot fields?](https://stackoverflow.com/questions/27230672/laravel-sync-how-to-sync-an-array-and-also-pass-additional-pivot-fields) – Maraboc Oct 05 '17 at 11:02
  • @Maraboc please see my edit – Jimmery Oct 05 '17 at 11:16
  • Try it like this : `foreach ($this->things as $index => $thing) { $thingIds[] = $thing->id; $order[] = ['order' => $index]; } $thong->things()->sync(array_combine($thingIds, $order));` :) – Maraboc Oct 05 '17 at 12:20
  • @Maraboc thanks for the suggestion - unfortunately that didnt work either :( any other ideas? – Jimmery Oct 05 '17 at 12:35
  • Is there an error or any thing ? – Maraboc Oct 05 '17 at 12:47
  • no error, just all the order values are 1... – Jimmery Oct 05 '17 at 12:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/156019/discussion-between-maraboc-and-jimmery). – Maraboc Oct 05 '17 at 12:50

0 Answers0