I want to combine my ordered products and display the order list.
Controller :
$orders = Order::where('customer_id', 1)->pluck('products');
print_r($orders);
This is what I receive:
Array (
[0] =>
[
{"id":3,"product_id":3,"size":"47","quantity":7,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"},
{"id":7,"product_id":4,"size":"47","quantity":8,"name":"Simple Regular Shirt","price":123,"thumbnail":"Thumbnail_91520734.jpg"}
]
[1] =>
[
{"id":9,"product_id":3,"size":"45","quantity":2,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"}
]
)
But I want.
Array (
[0] =>
[
{"id":3,"product_id":3,"size":"47","quantity":7,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"},
{"id":7,"product_id":4,"size":"47","quantity":8,"name":"Simple Regular Shirt","price":123,"thumbnail":"Thumbnail_91520734.jpg"},
{"id":9,"product_id":3,"size":"45","quantity":2,"name":"Simple Regular T-shirt","price":2200,"thumbnail":"Thumbnail_614291597.jpg"}
]
)
How I can do this?
I already tried a different way, but I can't do this. Firstly I was trying to convert it array and then use the array_marge() function for those arrays. but that array needs only two arrays but for my case, it is not specified how many arrays the user has given. And try to solve it with a loop (I just tried). I am new in this field.
CodePudding user response:
You could try
$orders = Order::where('customer_id', 1)
->pluck('products')
->values()
->flatten(1);
The pluck will return a collection, flatten with a depth of 1 will remove the nesting. values will reset the keys to sequential - (it's not strictly necessary here)
Laravel Docs - Collections - Values
Laravel Docs - Collections - Flatten
CodePudding user response:
Just add flatten()
after applying the query (with ->get()
):
$orders = Order::where('customer_id', 1)->get()->pluck('products')->flatten();
print_r($orders);
Side note:
Instead of print_r()
You can use dump()
to pretty print the output in your browser
$orders->dump(); //only dump
$orders->dd(); //dump and exit