Văn Đức Nguyễn
Văn Đức Nguyễn

Reputation: 54

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

Upvotes: 0

Views: 218

Answers (2)

Zar Ni Ko Ko
Zar Ni Ko Ko

Reputation: 352

I think , there is some promblems in your where clause change like this ,

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

Upvotes: 0

Poldo
Poldo

Reputation: 1932

You should check if user has value.

if ($user) {
 $username = $user->username;
} else {
 // add your logic here
}

Upvotes: 1

Related Questions