Reputation: 449
laravel 5.5 here is the collections:
$collections = collect(['name' => 'Rob'], ['nickname' => 'Robby']);
the both methods:
$collections->keyBy('name')
$collections->keyBy('nickname')
return equil result
Collection {#246 ▼
#items: array:1 [▼
"" => "Rob"
]
}
as me this looks like wrong...
Upvotes: 1
Views: 1257
Reputation: 2333
Your problem is that your collection is not well formatted, do it like this:
$collections = collect([ //main collection array
[ 'name' => 'Rob1', 'nickname' => 'Robby1' ] //object 0 inside collection array with well formated keys => values
]);
Now when you use:
$collections->keyBy('name')
$collections->keyBy('nickname')
It will work as spected
Upvotes: 0
Reputation: 449
so results are
Collection {#246 ▼
#items: array:2 [▼
"Rob" => array:1 [▼
"name" => "Rob"
]
"" => array:1 [▼
"nickname" => "Robby"
]
]
}
and
Collection {#246 ▼
#items: array:2 [▼
"" => array:1 [▼
"name" => "Rob"
]
"Robby" => array:1 [▼
"nickname" => "Robby"
]
]
}
still looks invalid searching in collections... and
$collections->keyBy('nick')
returns
Collection {#246 ▼
#items: array:1 [▼
"" => array:1 [▼
"nickname" => "Robby"
]
]
}
Upvotes: 0
Reputation: 432
I Think You Should pass one parameter as an array .. Try This
$collections = collect([['name' => 'Rob'], ['nickname' => 'Robby']]);
Upvotes: 1