nafeeur10's avatar

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?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

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]);
3 likes
neilstee's avatar

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. 😅

neilstee's avatar

@nafeeur10 try this:

$orderProductList = OrderProduct::where('order_id', $id)
	->pluck('id')
	->mapWithKeys(function($item) {
		return [$item => true]; 
	});

Please or to participate in this conversation.