i have two tables. School and Student.
When i fetch all Students
Student::all()->toJson();
I get a response with
[
{
"id": 1,
"school_id": 1,
"name": "Jhon"
}
]
But actually i would like to receive
[
{
"id": 1,
"school": {
"id": 1
},
"name": "Jhon"
}
]
I know i could do
Student::with(['school']);
But then it do an extra query to school table, which is not necessary, as i only need the school id, and not all other attributes.
You can override the
toArray
method in your model. The same thing also would be possible withtoJson
, buttoArray
gets called bytoJson
and in my opinion its nicer to do such stuff intoArray
Edit
To keep the model the same and only change to output (which is probably better)