skip to Main Content

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


  1. ->groupBy() as you’re using it is a Collection method, which accepts a string 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 a string.

    If your Student Model is properly handling father_details as JSON and converting it to an object automatically:

    $students = Student::get()->groupBy(function ($student) {
      return $student->father_details->father_name;
    });
    

    If your model is not doing that automatically, then you’ll need to do it manually:

    $students = Student::get()->groupBy(function ($student) {
      return json_decode($student->father_details)->father_name;
    });
    

    Or similar. This should group your data, one group for Pietro Hoeger and another group for Jace Bayer.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search