Michael
Michael

Reputation: 485

Laravel Trying to Get property of non object (from eloquent model)

Already read some of questions about this problem on stackoverflow and none of that answers apply to me. When I run:

$item_price = ItemPrice::where('item_name',$itemname)->first();

and then

$item_price->price

I get Trying to get property of non-object but when I run:

dd($item_price = ItemPrice::where('item_name',$itemname)->first());

It's returning object with attributes name, price etc. I don't really understand what is happening here.

Full code:

foreach ($inventorydecoded->assets as $asset) {

    $i = 0;
    $a = 0;
    while ($a < 1) {

      if ($inventorydecoded->descriptions[$i]->classid == $asset->classid) {
        $a = 1;
        $classid = $inventorydecoded->descriptions[$i]->classid;
        $itemname = $inventorydecoded->descriptions[$i]->market_hash_name;
        $tradable = $inventorydecoded->descriptions[$i]->tradable;
        $name_color = $inventorydecoded->descriptions[$i]->name_color;

  ;

      }
      $i++;
    } // end of while
      if ($tradable === 1 && strpos_arr($itemname, $blacklist) == false ) {
            $item_price = ItemPrice::whereItemName($itemname)->first();
      //     dd(ItemPrice::where('item_name',$itemname)->first());
            $items[] = ['assetid' => $asset->assetid,'classid'=> $classid,'itemname'=>$itemname,'name_color'=>$name_color,'price'=> $item_price->price];
            $serialized_inventory = serialize($items);

      }
  } // end of foreach

Upvotes: 1

Views: 401

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163968

You're using this query in loop, so one of those is empty and returns null. So you need to do simple check:

if (is_null($item_price)) {
    // There is no price for this item, do something.
}

Upvotes: 2

GabMic
GabMic

Reputation: 1482

Try this:

$item_price = ItemPrice::whereItemName($itemname)->first();

Upvotes: 0

Related Questions