0

I try to check if the record is not exist then i will do the insert, but it's not working.This is my code:

//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); 
            }
        }
  • You can check this link-> https://stackoverflow.com/questions/27095090/laravel-checking-if-record-exists – Payal Pandav Aug 18 '18 at 04:57
  • What you are getting in result please mention it too. – Hidayat Ullah Aug 18 '18 at 05:00
  • *I try to check if the record is not exist then i will do the insert* just a piece of advice, if you do this by code you had to deal with concurrency. Your `$data_antrian` may have dupes as the code executed at the same time, you can use the `noper` as a **primary key** to ensure only one is created. also, im curious with `$data_pemohon` as `->get()` will return empty collection instead of null in case it had no result cmiiw. – Bagus Tesa Aug 18 '18 at 06:25
  • if record is exist ? do you want to update it ? – Teoman Tıngır Aug 18 '18 at 07:38

1 Answers1

0

Not sure why are you using DB facade instead of Eloquent:

$data_antrian = App\Antrian_sp::where('noper', $noper)->firstOrFail();

If you don't have Model for antrian_sp table or just prefer DB facade, this should do it:

if ($data_antrian)
sskoko
  • 819
  • 6
  • 18