1

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

3
  • Is $user an eloquent model? If so, do you also have a model set up for csstats? Commented Jul 22, 2018 at 16:32
  • $user is eloquent model. I think i getting this error becouse i'm using first. But i don't get it how to make work with "get();" Commented Jul 22, 2018 at 16:35
  • Do you have a model set up for csstate? Commented Jul 22, 2018 at 16:37

2 Answers 2

1

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; 
Sign up to request clarification or add additional context in comments.

Comments

0

you can check that with isset()

like that

if(isset($user->HeadHits ) ) 

Comments

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.