0

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
10
  • it seems an order has no order_status. Commented Apr 20, 2020 at 13:44
  • 1
    $order->order_status->name is the correct syntax, but if $order->order_status is null, you can't call null->name. Add some code to make sure $order->order_status exists; don't assume it does. Commented Apr 20, 2020 at 13:46
  • The order belongsTo orderStatus and i get it. we see it in the result. @TsaiKoga Commented Apr 20, 2020 at 13:46
  • what about all orders you get, is there one of them without order_status? Commented Apr 20, 2020 at 13:48
  • 1
    Your code shows a single order, but you're calling ->get(), which can get multiple orders. If you only want to get orders that have an order status, you need to include has('orderStatus'), otherwise, it's possible that one of your orders does not have an orderStatus object. Also, your output is a JSON translation. In php, this would be $order->orderStatus->name Commented Apr 20, 2020 at 13:51

1 Answer 1

1

The problem is that your total price always exists as a field, but order_type might be empty.

You can use ternary for a quick fall-back in your code like:

!empty($order->orderStatus)?$order->orderStatus->name:null;
Sign up to request clarification or add additional context in comments.

2 Comments

It's probably $order->orderStatus, not $order->order_status. Look at the with() clause, with('orderStatus'). The output in the code is a JSON representation, which converts relationships to snake_case. Also, !empty() is unnecessary; can just be $order->orderStatus ? $order->orderStatus->name : ''
Oh yeah nice catch, thank you for pointing out. My bad missed the relation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.