Link to home
Create AccountLog in
PHP

PHP

--

Questions

--

Followers

Top Experts

Avatar of Ricky Nguyen
Ricky Nguyen🇦🇺

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

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


ASKER CERTIFIED SOLUTION
Avatar of Ricky NguyenRicky Nguyen🇦🇺

ASKER

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.

PHP

PHP

--

Questions

--

Followers

Top Experts

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.