Link to home
Start Free TrialLog in
Avatar of Ricky Nguyen
Ricky NguyenFlag for Australia

asked on

Laravel Pivot Table Update with Attachment of Multi-dimension Array - Array to String Conversion Error

Hi Experts,

I'm having trouble creating a multi-dimension array to update a pivot table in Laravel with its corresponding attributes.

What I'm looking to do is have users select multiple entries from a list and once they submit their selections, I would like to add the "assigned_date" attributes to each selection when saving these records to the pivot table.


My Class Method:
public function assignUserAsset()
    {

        //Assume we can find this
        $user = User::find(1);
        $assignDate = date('Y-m-d');
        $attrib = ['assigned_date' => $assignDate];
        $assetArray = [1,2];

        //Attach current date to each selection
        $arr = [];
        foreach ($assetArray as $key) {
            $arr[] = [$key=>$attrib];
        }

        //Create entry in pivot table
        $user->assets()->attach($arr);


    }

Open in new window



dd($arr)
array:2 [▼
  0 => array:1 [▼
    1 => array:1 [▼
      "assigned_date" => "2020-02-27"
    ]
  ]
  1 => array:1 [▼
    2 => array:1 [▼
      "assigned_date" => "2020-02-27"
    ]
  ]
]

Open in new window



Error
User generated image

I'm trying to follow this documentation here.

Specifically under section Many to Many Relationships - Attaching / Detaching

Documentation Sample

$user = App\User::find(1);

$user->roles()->detach([1, 2, 3]);

$user->roles()->attach([
    1 => ['expires' => $expires],
    2 => ['expires' => $expires],
]);

Open in new window



Can you please help understand what I'm doing wrong?

Thanks,
Ricky
ASKER CERTIFIED SOLUTION
Avatar of Ricky Nguyen
Ricky Nguyen
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial