php - 'Trying to get property 'value_type1' of non-object' in laravel
I have the following query running in a function:
$sensor = Sensor::where('id', $measurement->sensor_id)->with('sensorType', 'sensorType.valueType1', 'sensorType.valueType2')->first();
This returns the following response:
{
"id": 1,
"name": "DHT22 Kantoor",
"sensor_type_id": 1,
"active": 1,
"organisation_id": 1,
"disabled_until": null,
"created_at": null,
"updated_at": "2020-07-15T11:12:33.000000Z",
"sensor_type": {
"id": 1,
"name": "DHT22",
"value_1_type_id": 1,
"value_2_type_id": 2,
"created_at": null,
"updated_at": null,
"value_type1": {
"id": 1,
"name": "Temperatuur",
"unit": "?�C",
"created_at": null,
"updated_at": null
},
"value_type2": {
"id": 2,
"name": "Luchtdruk",
"unit": "Pa",
"created_at": null,
"updated_at": null
}
}
I am trying to get the 'Temperatuur' that is in this response in the following way:
$affValue = $sensor->sensor_type->value_type->name;
But this gives me the following error:
Trying to get property 'value_type1' of non-object
I've tried doing the following:
$sensor->name
returns DHT22 Kantoor
$sensor->sensor_type->id
gives the same error as before
Am I trying to access this value wrong? Or is there a diffrent solution?
Answer
Solution:
I got it working now.
Instead of using sensor_type
i needed to use sensorType
The same for value_type1
, it needed to be valueType1
So instead of using the name that's in the response you need to use the name that is in the App\SensorType
.