Skip to content
Advertisement

Trying to get property of non-object when trying to select a value from the result

I have a problem with the function. I make a request to select from the database, the selection is normal and there is a second code that should take the value of the price column from the result, but the problem is that I get an error as a result: Trying to get property of non-object.

My code:

$betitem = DB::table('items')->where('status', 0)->where('price', '>=', 10)->orderByRaw('RAND()')->take(1)->get();
$green_tickets = $betitem->price;

If write var_dump($betitem[0]); exit; i received:

object(stdClass)#584 (13) { ["id"]=> int(548) ["assetid"]=> string(11) "18235855849" ["market_hash_name"]=> string(15) "Staff of Gun-Yu" ["classid"]=> string(231) "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KW1Zwwo4NUX4oFJZEHLbXK9QlSPcU_phVWSVXvTO2j0IDeXFN_IB1ovbOrLDhp3v7HYylD4OOhkYGbmPm7PrTfnW5I1854hO7-_IH4h0agqh8DJDyiZNnLbAE8M13Q-Ae4wrq7g5Pq7cufnCRm7nZ3tCyPlhSyhx1IabZrjPKaQVqAR_se2_6rU3g" ["price"]=> float(26.4) ["steamid"]=> string(1) "1" ["type"]=> string(4) "card" ["bot"]=> string(1) "1" ["status"]=> int(0) ["created_at"]=> string(19) "2020-02-27 01:47:12" ["updated_at"]=> string(19) "2020-03-14 17:41:25" ["is_withdraw"]=> int(0) ["is_raffling"]=> int(0) }

How i understand the problem arises because the result is received in an array. But then how to fix this error and get the result from the price column?

Advertisement

Answer

Since $betitem has an object inside an array, you can do

$green_tickets = $betitem[0]->price;

Or you can use the first() method to get the first row matching your conditions.

$betitem = DB::table('items')->where('status', 0)->where('price', '>=', 10)->orderByRaw('RAND()')->take(1)->first();

$green_tickets = $betitem->price;

Also, I can see an extra before DB. You can add use DB; before declaration of your class and it should run just fine. Make sure this DB alias exists in your config/ app.php.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement