Reputation: 302
Hello everyone am newly in laravel and i am trying to get data.using state ID please explain me with all Model with relationship each-other with example i have tables like this
1- states table
1- id
2-name
2- cities table
1- id
2-name
3- state_cities pivot table
1-id
2-sate_id
3-city_id
4- locations table
1-id
2-name
5- city_locations pivot table
1-id
2-city_id
3-location_id
6- pincodes table
1-id
2-pincode
7- location_pincodes table
1-id
2-location_id
3-pinecode_id
And this is my Controller
$states_with_cities = $states_with_cities->load(['cities.cityName','location.locationName'])->where('id',1)->get();
$states_with_cities->transform(function($states_with_cities) {
return [
'state_id' => $states_with_cities->id,
'state_name' => $states_with_cities->name,
'cities' => $states_with_cities->cities->map(function($cities,$location) {
return [
'city_id' => $cities->city_id,
'city_name' => $cities->cityName->name,
'location' => $location->locationName->map(function($locationName) use($location) {
return [
'location_id' => $location->location_id,
'location_name' => $locationName->locationName->name
];
})
];
}),
];
});
and that is error which is am geting
"message": "Trying to get property of non-object",
"exception": "ErrorException",
"file": "D:\\xampp\\htdocs\\samudaay-backend\\app\\Http\\Controllers\\API\\PincodeController.php",
"line": 32,
Upvotes: 0
Views: 167
Reputation: 1443
$states_with_cities = $states_with_cities->load(['cities.cityName','location.locationName'])->where('id',1)->get();
$states_with_cities->transform(function($states_with_cities) {
return [
'state_id' => $states_with_cities->id,
'state_name' => $states_with_cities->name,
'cities' => $states_with_cities->cities->map(function($cities,$location) {
// Location is the 'key' of the object in the collection. So it probably will be something like '0' or '1'.
return [
'city_id' => $cities->city_id,
'city_name' => $cities->cityName->name,
'location' => $location->locationName->map(function($locationName) use($location) {
//What you actually do here is: 0->locationName->map(...). This will result in your error
return [
'location_id' => $location->location_id,
'location_name' => $locationName->locationName->name
];
})
];
}),
];
});
$location in the first map function is the key of the object it is iterating at the moment. (see: https://laravel.com/docs/5.6/collections#method-map) So on line 32 you are trying to call a property on the key variable (which will probably be '0' or '1' or something.) As that is not an object, it will result in the error you get.
Also, trying to map the locationName property is not going to work as expected. locationName is a property and not an eloquent collection.
You should probably try it like this:
'location' => [
'location_id' => $location->location_id,
'location_name' => $location->name
];
})
Upvotes: 1