Reputation: 4885
I need to group the following rows based on the type, but I need the Collection to just have the item and not an array with 1 item inside it.
Example database rows:
id location_id type section_id content
0 2 telephone 1 123135145
1 2 mobile 1 245446546
Expected Result:
[
'telephone' => [
'id' => 0,
'location_id' => 2,
'type' => 'telephone',
'section_id' => 1,
'content' => 123135145
],
'mobile' => [
'id' => 1,
'location_id' => 2,
'type' => 'mobile',
'section_id' => 1,
'content' => 245446546
]
]
Actual Result:
[
'telephone' => [
0 => [
'id' => 0,
'location_id' => 2,
'type' => 'telephone',
'section_id' => 1,
'content' => 123135145
]
],
'mobile' => [
0 => [
'id' => 1,
'location_id' => 2,
'type' => 'mobile',
'section_id' => 1,
'content' => 245446546
]
]
]
Here is my Eloquent query
$contactDetails = $this->contactDetails()->where([ 'section_id' => 1 ])->get()->groupBy('type');
The contactDetails()
method is relationship:
public function contactDetails(){
return $this->hasMany(WebsiteLocationContactDetails::class);
}
Upvotes: 0
Views: 219
Reputation: 730
I'm not an eloquent expert but I think this result is correct and that you should simply adjust the result after you get it.
Try it with this fiddle.
<?php
$array = [
'telephone' => [
0 => [
'id' => 0,
'location_id' => 2,
'type' => 'telephone',
'section_id' => 1,
'content' => 123135145
]
],
'mobile' => [
0 => [
'id' => 1,
'location_id' => 2,
'type' => 'mobile',
'section_id' => 1,
'content' => 245446546
]
]
];
foreach($array as $k => $v) {
$newArray[$k] = $v[0];
}
echo '<pre>'; print_r($newArray); echo '</pre>';
?>
Upvotes: 1