I have a Device model and a Readings model which are connected by a many-to-many relationship. I am working on an API which returns an array of all the registered devices to a particular user. What i want is a field in the response which shows the last entry in the readings table.
This is the method which returns the response.
public function getUserDevices($user_id){
$devices = Device::where('user_id',$user_id)->get();
return response()->json($devices);
}
The response that i am currently getting.
[
{
"id": 2,
"user_id": 1,
"device_name": "My Device",
"device_type": "Sensor",
"status": 1,
"created_at": "2018-05-01 14:39:35",
"updated_at": "2018-05-13 17:56:56",
"device_key": "60:01:94:37:D1:34",
"actuator": 0,
"mode": 1
},
{
"id": 3,
"user_id": 1,
"device_name": "Home Device",
"device_type": "Sensor",
"status": 1,
"created_at": "2018-05-01 14:40:25",
"updated_at": "2018-05-12 13:42:00",
"device_key": "60:01:94:37:D1:35",
"actuator": 0,
"mode": 0
}
]
The response that i want.
[
{
"id": 2,
"user_id": 1,
"device_name": "My Device",
"device_type": "Sensor",
"status": 1,
"created_at": "2018-05-01 14:39:35",
"updated_at": "2018-05-13 17:56:56",
"device_key": "60:01:94:37:D1:34",
"actuator": 0,
"mode": 1
"reading":{ <--- This is what i want in every item of the collection
"temp": 45,
"hum" : 60
}
},
{
"id": 3,
"user_id": 1,
"device_name": "Home Device",
"device_type": "Sensor",
"status": 1,
"created_at": "2018-05-01 14:40:25",
"updated_at": "2018-05-12 13:42:00",
"device_key": "60:01:94:37:D1:35",
"actuator": 0,
"mode": 0
"reading":{ <--- This is what i want in every item of the collection
"temp": 35,
"hum" : 76
}
}
]
Any help would be appreciated. Thanx
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire