I have an students table like:
id | name | father_details |
---|---|---|
1 | A | {"father_email":"[email protected]", "father_name":"Pietro Hoeger"} |
2 | B | {"father_email":"[email protected]", "father_name":"Jace Bayer"} |
3 | C | {"father_email":"[email protected]", "father_name":"Pietro Hoeger"} |
4 | D | {"father_email":"[email protected]", "father_name":"Pietro Hoeger"} |
I want to try group by father name from json:
$students = Student::get()
->groupBy('father_details->father_name'); // This Group by is not working
But the father name is not group by in key what can i do for this ?
2
Answers
->groupBy()
as you’re using it is aCollection
method, which accepts astring
for the property/attribute you wish to group by. It is not a builder method, so it has no idea that'father_details->father_name'
is supposed to be evaluating the JSON, and$student['father_details->father_name']
is definitely not valid. So yeah,->groupBy('father_details->father_name')
is not going to work.If you check the documentation You can use a
callback
function instead of astring
.If your
Student
Model is properly handlingfather_details
as JSON and converting it to an object automatically:If your model is not doing that automatically, then you’ll need to do it manually:
Or similar. This should group your data, one group for
Pietro Hoeger
and another group forJace Bayer
.Try
$students = Student::select('father_details->father_name as father_name')->groupBy('father_name')->get();
https://laracasts.com/discuss/channels/eloquent/can-i-group-by-a-json-property