Search code examples
phpjsonlaraveleloquentlaravel-5.3

Laravel Nested Query Builder Json Response


I am trying to get a certain structure from a query builder which looks as:

{
  "status": "success",
  "data": {
    "id": 1,
    "email": "[email protected]",
    "birth_date": "1992-08-17",
    "gender": "M",
    "is_active": 1,
    "role": {
      "id": 1,
      "name": "Admin",
      "created_at": "2017-01-11 15:16:14",
      "updated_at": null
    }
  }
}

As you can see, i need for the relationship to be nested, in this case User to Roles.

I can get this structure using eager load with User::with('role').

I have this query but it returns everything in one column. Is there any way i can get this same structure using query builder? Is using eager load bad practice?

User::select('users.id', 'users.full_name')
    ->join('roles as r', 'r.id', '=', 'users.role_id')
    ->where('users.id', $user_id)
    ->get();

Thanks in advance.


Solution

  • I'd say eager loading is the best practice. It's readable and maintainable way to work with data, it returns conveniently structured data etc.

    Of course, you can achieve the same result with Query Builder and even raw queries, but at the end of the day, you'll get an unmaintainable app.

    So, I'd recommend you to stay with:

    User::with('role')->get();