Laravel Join Relations for JSON

236 Views Asked by At

I am using Eloquent Relationship in Laravel to output my data to JSON. When I use Eloquent Relations they show up inside JSON as an object but I need only JSON output with variables inside without object or json, As shown below:

   {
    "id": 1,
    "name": "Status changed",
    "history_id": null,
    "admin_id": 4,
    "created_at": "2021-05-21T16:10:08.000000Z",
    "updated_at": "2021-04-21T16:10:08.000000Z",
    "type_id": 2,
    "comment": "Horoshiy Specialist",
    "result_id": 2,
    "result_comment": "Prowerili anketu i obrazowanie",
    "start_time": null,
    "end_time": null,
},

Instead of this (the result for the relation one to many toJSON in LARVEL) :

 $activity = Activity::find(1)->load('history')->toJSON();

result:

{
    "id": 1,
    "name": "Status changed",
    "history_id": null,
    "admin_id": 4,
    "created_at": "2021-05-21T16:10:08.000000Z",
    "updated_at": "2021-04-21T16:10:08.000000Z",
    "history": [
        {
            "id": 1,
            "type_id": 2,
            "comment": "Horoshiy Specialist",
            "result_id": 2,
            "result_comment": "Prowerili anketu i obrazowanie",
            "start_time": null,
            "end_time": null,
        }
    ]
},

Any ideas how this can be done ? I can do it using DB join (), but is there a way to do it using Eloquent? Besides :

 $activity = \App\Models\Activity::find(1)
 ->join('activity_history',  'activity_history.id', '=', 
          'activities.history_id')->select('*')->get()
 ->toJSON();

Because this is not the best way to do it, because I am using the column names and the table names, which I have to go to the DB behind to look at them

1

There are 1 best solutions below

1
On BEST ANSWER

You can around doing this by flattening the array when you get that result. Let's imagine you $object->history to get the result with the history relationship, and simply do:

Arr::dot($object->history);

So you'll get an array like:

{
    "id": 1,
    "name": "Status changed",
    "history_id": null,
    "admin_id": 4,
    "created_at": "2021-05-21T16:10:08.000000Z",
    "updated_at": "2021-04-21T16:10:08.000000Z",
    "history.id": 1,
    "history.type_id": 2,
    "history.comment": "Horoshiy Specialist",
    "history.result_id": 2,
    "history.result_comment": "Prowerili anketu i obrazowanie",
    "history.start_time": null,
    "history.end_time": null,
}