How to make associative array from pluck in Laravel
$orderProductList = OrderProduct::where('order_id', $id)->pluck('id')->all();
Here I am getting result like this:
array:1 [
0 => 1,
1 => 2
]
ID Array.
But I want to make it Associative Array like the example:
array:1 [
1 => true,
2 => true
]
All array id will be true. But while I will access it like this: $orderProductList[1] it will give me true.
How can I get this?
pluck can take two arguments, the value and key columns, note that the key is the second argument e.g.
$orderProductList = OrderProduct::where('order_id', $id)
->pluck('column_that_is_true', 'id')->all();
Where does the true value come from (in the context of the database table)?
If true is arbitrary, then a mapWithKeys might just be easier:
$orderProductList = OrderProduct::where('order_id', $id)
->pluck('id')
->mapWithKeys(fn ($id) => [$id => true]);
Oh, @tykus already answered the same answer as mine. pretty sure I didn't see that earlier that's why I still did the mapWithKeys solution. 😅
@nafeeur10 try this:
$orderProductList = OrderProduct::where('order_id', $id)
->pluck('id')
->mapWithKeys(function($item) {
return [$item => true];
});
Please or to participate in this conversation.