插入数据时如何检查数据是否已经存在

时间:2019-09-20 14:28:16

标签: php laravel

我想问一下如果输入的数据有相同的无法插入的情况,该如何检查数据。

我的代码:

$obj = new Pengajuan();
//   $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
    $status = "Tersmpan";
} else {
    $status = "Gagal";
}
echo json_encode(array("status" => $status));

2 个答案:

答案 0 :(得分:0)

public function store(Request $request)
{
    $this->validate($request,[
        'id_nasabah'=>'required|exists:your_table_name,id',
        'tgl_pengajuan'=>'more_validations',
        'besar_pinjaman'=>'more_validations',
    ]);

    //if $this->validate() fails, it will return a response 422 code error
    //else it will continue with the creation of your object 

    //is a good idea to use a try-catch in case of something goes wrong
    try
    {
        $pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));

        return response->json([
            'pengajuan'=>$pengajuan,
            'status'=>'Tersmpan',
        ],200);//return a http code 200 ok
    }
    catch(Exception $e)
    {
        //'message'=>'this will return what is the error and line'
        return response()->json([
            'message'=>$e->getMessage().'/'.$e->getLine(),
            'status'=>'Gagal',
        ],422);
    }
}

答案 1 :(得分:0)

上面的代码添加如下所示的验证:

 $this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;

然后是您的控制器代码的其余部分。