PHP检查数据库中是否存在

时间:2020-09-28 12:41:00

标签: php laravel

我正在尝试检查数据库中是否存在某些内容。基本上,我想为用户添加设备(如果该设备不存在),而我正在尝试这样做:

public static function checkDevice($userId, $tokenId){
        $devices = UserDevices::where('user_id', $userId)->get();
    
        $notExists = '';

        foreach ($devices as $key => $d) {
            if(!$d->ip_address === SecureAgent::getIP() && $d->mac_address === SecureAgent::getMAC() && $d->device === SecureAgent::getDevice() ){
                $notExists = 'User device not found!';
            }
        }
   }

所以我需要检查这个IP,Mac和设备是否已经添加到数据库中,如果它们与其他任何都不一样,我将需要它们添加到数据库中,例如:

if($notExists === 'User device not found'){
  self::addDevice() // I'm calling another function to do that job
}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我是这样做的:

try {
            UserDevices::where('user_id', $userId)->where('ip_address', SecureAgent::getIP())->where('mac_address', SecureAgent::getMac())->where('browser', SecureAgent::getSurfer())->firstOrFail();
        } catch (\Exception $e) {
            self::addDevice($userId, $tokenId);
        }
相关问题