如何检查记录在laravel中是否存在?

时间:2018-08-14 11:23:39

标签: ajax laravel select insert record

我有一个问题,我不知道我的代码有什么问题,我尝试找出要插入数据库的数据是否存在,如果不存在,我想插入它。但是,即使数据库中不存在数据,我也无法插入数据。这是我的代码:

$data_pemohon       = DB::table('data_pemohon')->select('*')->where('noper', $noper)->get();
if(is_null($data_pemohon)){
    $tambah_data_pemohon = DB::table('data_pemohon')->insert($data);
}else{
    echo "the data is exist!";      
}

请帮帮我。谢谢。

3 个答案:

答案 0 :(得分:1)

$data_pemohon = DB::table('data_pemohon')->where('noper', $noper)->exists();
if(!$data_pemohon){
    $tambah_data_pemohon = DB::table('data_pemohon')->insert($data);
}else{
    echo "the data is exist!";      
}

答案 1 :(得分:1)

它可能与您的问题无关,但我建议您使用'unique' validation rule。 一个非常简单的用法是这样的:

$validator = Validator::make($data, [
    'noper' => 'unique:data_pemohon:noper',
]);
if ($validator->fails()) {
    // ... Handle the error
}
// ...Insert your data

我建议阅读文档,以更好地了解Laravel的验证过程。

答案 2 :(得分:0)

-> get()方法返回集合(甚至为空),因此您必须将其更改为-> first()(如果未找到=>返回null ),也可以使用 if(count($ data_pemohon)=== 0)检查条件,然后插入