Skip to content
Advertisement

Trying to get property of non-object in laravel 5.6

I get data from database:

$user = DB::table('view_users')->where([
                            'id'        => $friend->user_id,
                            'type'      => $friend->user_type,
                            'del_flg'   => 0,
                            'status'    => 1
            ])->first();
$username = $user->username;

but i have a error:

Trying to get property 'username' of non-object

When I use dd($user->username), It still have result as string. After I use var_dump($user);exit; to check type of varible $user, the result is a object.

Can you help me find the problem? Thank you very much

Advertisement

Answer

You should check if user has value.

if ($user) {
 $username = $user->username;
} else {
 // add your logic here
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement