Search code examples
laravelcollections

Laravel collection Group by with json


I have an students table like:

id name father_details
1 A {"father_email":"abc@example.com", "father_name":"Pietro Hoeger"}
2 B {"father_email":"abcd@example.com", "father_name":"Jace Bayer"}
3 C {"father_email":"abce@example.com", "father_name":"Pietro Hoeger"}
4 D {"father_email":"abcf@example.com", "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 ?


Solution

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