1

I got an Order object which has many-to-many relation with products:

public function products() {
       return $this->belongsToMany('App\Product', 'order_products')
                   ->withPivot('count', 'price');
   }

I accept in request an array with products, then I should attach it to the order. But if I got an array, not collection, then how should I do this right way? I can do it via loop in $request->products, but it seems to be wrong for me.

To be exact, I have an array:

$products = [
  ['id' => 4, 'count' => 5],
  ['id'=>5, 'count' => 3]        
];

How to do an $order->products->attach() without any loop?

1 Answer 1

3

Both attach and detach accept an array of ids:

$ids = collect($request->products)->pluck('id');

$order->products()->attach($ids);
Sign up to request clarification or add additional context in comments.

1 Comment

also Illuminate\Support\Arr::pluck and array_pluck for completeness :)

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.