Understanding "Trying to get property of non-object" and preventing it
laravel-4, php
Solution
“Trying to get property of non-object”, it means you are trying to get something that doesn't exist
. In OOP's classes have object and object have properties associated with them. You can access these properties if they exist.
In your case it doesn't exist. To overcome this use isset() before accessing the values like:
isset($order->order_id) ? $order->order_id : 'NA';
In this case if the property doesn't exist than code will not throw error, instead it will go in else part and print NA
Problem
First of all I want to apologies for the thread and I know that there are tons of similar thread on SO. After reading on them I can't really understand what happens in my site. Framework is `Laravel-4.2` Couple of hours site was okay and everything works perfectly. Now few of the pages get `Trying to get property of non-object` when I try to access them. Not all pages.. just 2-3. For example this is in my controller to display all orders. ``` public function orders() { $orders = Order::select('*')->orderBy('order_id', 'DESC')->paginate(5); return View::make('site.admin.orders', [ 'orders' => $orders ]); } ``` And this is in my view ``` @foreach($orders as $order) <tr> <td class="text-center">{{ $order->order_id }}</td> <td class="text-center">{{ $order->user->username }}</td> // few more <td>`s </tr> @endforeach ``` The error is on first `<td>`: ``` <td class="text-center">{{ $order->order_id }}</td> ``` Exact same piece of code works on other site ( copy of this one ). I know in this situation I can just change `$order->order_id` to `$order['order_id']`... Why is this happen? How to prevent it? I don't understand the nature of this error. And it is very strange to me because this works on exact copy of the site. Update: This is my Model: ``` public function getOrderData($data) { $dataArray = json_decode($data, true); $data = json_decode($data); $arrayKeys = array_keys($dataArray); $arrayKeys = array_filter($arrayKeys, function($value) { return ($value !== 'shipping'); }); $productIds = implode(',', $arrayKeys); $products = DB::table('products') ->leftjoin('category', 'products.category_id', '=', 'category.category_id') ->leftjoin('sub_category', 'products.sub_cat_id', '=', 'sub_category.sub_cat_id') ->where('product_id',$productIds) ->get(); foreach ($products as $item) { if(!in_array($item->product_id, $arrayKeys)) continue; $dataArray[$item->product_id]['category'] = $item->category_name; $dataArray[$item->product_id]['sub_category'] = $item->sub_cat_name; } return json_decode(json_encode($dataArray)); } ```