I use laravel framework. I can retrieve data from database with relationship with this code:
$orders = Order::with('orderType', 'orderStatus', 'user')->get();
The result of the above command is:
[
{
"id":16,
"shop_id":1,
"user_id":0,
"delivery_cost":null,
"address":null,
"latitude":null,
"longitude":null,
"total_price":655000,
"total_price_off":551000,
"order_status_id":5,
"order_type_id":3,
"reserve_id":null,
"created_at":"1399-02-01 13:25:51",
"order_type":{
"id":3,
"name":"admin"
},
"order_status":{
"id":5,
"name":"system"
},
"user":null
}
]
My php code is:
foreach($orders as $order){
echo $order->order_status_name; \\ I get error for this line;
}
Now my problem is how can i access the name field in order_status? when i want access to total price i write this code
$order->total_price
and get the total price without any error, but when is write this code
$order->order_status->name
i get this error:
Trying to get property 'name' of non-object
$order->order_status->nameis the correct syntax, but if$order->order_statusisnull, you can't callnull->name. Add some code to make sure$order->order_statusexists; don't assume it does.->get(), which can get multiple orders. If you only want to get orders that have an order status, you need to includehas('orderStatus'), otherwise, it's possible that one of your orders does not have anorderStatusobject. Also, your output is aJSONtranslation. In php, this would be$order->orderStatus->name