-3

I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.

My code:

$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));
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
AndrewLee
  • 31
  • 1
  • 9
  • 2
    Possible duplicate of [Laravel Checking If a Record Exists](https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists) – Harun Yilmaz Sep 20 '19 at 14:32
  • Check out the validation rule for `exists`: https://laravel.com/docs/5.8/validation#rule-exists. – Tim Lewis Sep 20 '19 at 14:32

2 Answers2

0

try this:

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);
    }
}
OMR
  • 11,736
  • 5
  • 20
  • 35
0

Above of the code add a validation like below:

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

And then rest of your controller code.

Tanvir Ahmed
  • 969
  • 12
  • 24