Mynde Mindaugelis
Mynde Mindaugelis

Reputation: 105

Laravel if database table empty

I have a simple database query to put out some stuff from database like example:

$user->HeadHits = DB::table('csstats AS cs')
->where('cs.steamid', '=', $user->steam_id)
->select("cs.h_1")
->first()->h_1;

And blade:

@if ($user->HeadHits == 0)
0%
@else
<?php echo number_format($user->HeadHits / $user->AllHits * 100,2); ?>%
@endif

But i'm getting error if user steam_id not find in database:

Trying to get property of non-object

Any suggest? Thanks

Upvotes: 1

Views: 1991

Answers (2)

Rwd
Rwd

Reputation: 35190

This is because when you use DB (Query Builder) and first it will return null if the row can not be found.

You would need to add a check in to see if the value exists:

$cs = DB::table('csstats AS cs')
    ->where('cs.steamid', '=', $user->steam_id)
    ->select("cs.h_1")
    ->first();

$user->HeadHits = $cs ? $cs->h_1 : 0;

A shorter approach would be to use value():

$user->HeadHits = DB::table('csstats AS cs')
    ->where('cs.steamid', '=', $user->steam_id)
    ->value('h_1') ?: 0;

Lastly, just a FYI but you don't need to be explicit with adding the table alias before the column name since you're only querying one table. Also, you don't need to add = with where() as it will assume this is the operator that should be used. Ultimately, you can reduce your code to something like:

$user->HeadHits = DB::table('csstats')->where('steamid', $user->steam_id)->value('h_1') ?: 0; 

Upvotes: 1

Abdi
Abdi

Reputation: 608

you can check that with isset()

like that

if(isset($user->HeadHits ) ) 

Upvotes: 0

Related Questions