如何使用laravel检查数据库中是否存在记录?

如何使用laravel检查数据库中是否存在记录?,laravel,select,insert,Laravel,Select,Insert,我尝试检查记录是否不存在,然后我将进行插入,但它不起作用。这是我的代码: //check if nomor permohonan is exist $data_pemohon = DB::table('data_pemohon')->select('*')->where('noper', $noper)->get(); if(is_null($data_pemohon)){ return response(null);

我尝试检查记录是否不存在,然后我将进行插入,但它不起作用。这是我的代码:

//check if nomor permohonan is exist
        $data_pemohon = DB::table('data_pemohon')->select('*')->where('noper', $noper)->get();
        if(is_null($data_pemohon)){
            return response(null);          
        }else{
            $data_antrian   = DB::table('antrian_sp')->select('*')->where('noper', $noper)->first();
            if(is_null($data_antrian)){
                $nama        = DB::table('data_pemohon')->select('nama')->where('noper', $noper)->first();
                $status      = DB::table('data_pemohon')->select('status_paspor')->where('noper', $noper)->first();
                $data       = array('tanggal'=>$tanggal, 'jam'=>$jam, 'noper'=>$noper, 'nama'=>$nama->nama, 'status'=>$status->status_paspor);
                $add_antrian= DB::table('antrian_sp')->insert($data);

                if($add_antrian){
                    return response($data_pemohon);
                }else{
                    echo "error";           
                }
            }else{
                return response(1); 
            }
        }

不确定为什么要使用DB facade而不是雄辩:

$data_antrian = App\Antrian_sp::where('noper', $noper)->firstOrFail();
如果您没有antrian_sp表的模型,或者只是更喜欢DB facade,那么应该这样做:

if ($data_antrian)

你可以检查这个链接->你在结果中得到了什么,请提一下。我试着检查记录是否不存在,然后我会做插入只是一个建议,如果你这样做的代码,你必须处理并发性。您的
$data\u antrian
可能有两个副本作为同时执行的代码,您可以使用
noper
作为主键,以确保只创建一个。另外,我对
$data\u pemohon
很好奇,因为
->get()
将返回空集合,而不是null,以防它没有结果cmiiw。如果记录存在?你想更新它吗?