0

I'm trying to update multiple rows but I face an array to string conversion error. Donation to Donation Items is a one-to-many relation and up to 5 types of items may be updated. I've already tried using solution from Update multiple rows of database in Laravel and used the saveMany() method but I'm still not able to update the given rows.

Here's what I tried:

    $n = 0;
    $donationItems = DonationItems::where('donation_id', $donationId)->get();
    foreach ($donationItems as $item) {

        $itemName = $r->get('item-name');
        $itemQuantity = $r->get('item-quantity');

        $item->name = $itemName;
        $item->quantity = $itemQuantity;
        $item->donation_id = $donation->id;

        $donation->donationItems()->save($item);

        $n += 1;
    }
3
  • stackoverflow.com/a/46828717/4232159 Commented Oct 21, 2017 at 12:22
  • What output did you've get when you've var_dump($item) inside your foreach? Commented Oct 21, 2017 at 12:47
  • Same error when I used var_dump($item). When I tried dd($item) it gives the original value of the fields that were previously filled. In this case, I had one record of item. #attributes: array:6 [▼ "id" => 3 "name" => "wwwwwwwwwwwww" "quantity" => 5 "created_at" => "2017-10-20 16:12:10" "updated_at" => "2017-10-20 19:27:25" "donation_id" => 3 ] #original: array:6 [▼ "id" => 3 "name" => "wwwwwwwwwwwww" "quantity" => 5 "created_at" => "2017-10-20 16:12:10" "updated_at" => "2017-10-20 19:27:25" "donation_id" => 3 ] Commented Oct 21, 2017 at 12:57

2 Answers 2

0

Change your line

$donation->donationItems()->save($item);

For

$item->save();

Since you already set the donation_id on your $item, you don't need to save them through the relation

Sign up to request clarification or add additional context in comments.

1 Comment

It still gives me the array to string conversion error though.
0

You can just use update() method which will create just one query instead of N queries:

DonationItems::where('donation_id', $donationId)
    ->update([
        $item->name = $r->item-name;
        $item->quantity = $r->item-quantity;
        $item->donation_id = $donation->id;
    ]);

This will work as long as you're properly using $fillable array in the model:

protected $fillable = ['name', 'quantity', 'donation_id'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.