Home > database >  how can i use the array in where statement in laravel 9
how can i use the array in where statement in laravel 9

Time:02-02

here is the data

req[
    {
        "_id": "123",
        "_ar_id": "111",
        "_val": "10",
        "ar_date": "2023-02-02"
    },
    {
        "_id": "1234",
        "_ar_id": null,
        "_val": "0",
        "ar_date": "2023-02-02"
    }
]


$validator = Validator::make($req->all(), [
            'req.*._id' => 'required',
            'req.*._val' => 'required',
            'req.*.ar_date' => 'required',
        ]);
        
if ($validator->fails()) {
     return response()->json(['stat' => 0,'msg' => $validator->errors(), 'data' => "Please input required details" ]);
        }

since i validate the request, how can i use it in where to ?

here's the code

$record = ArRecordCount::where('ar_list_id', $list_id)->where('ar_date', $ar_date)->first();

and if has record then it will update, if no record then delete

CodePudding user response:

check if there is a record in the database for each element. If the record exists, you can update it, if not, you can delete it. Here's an example:

foreach ($req as $request) {
    $record = ArRecordCount::where('ar_list_id', $list_id)
                           ->where('ar_date', $request['ar_date'])
                           ->first();
    if ($record) {
        // update the record
    } else {
        // delete the record
    }
}

CodePudding user response:

Update if exist or create if not

ArRecordCount::updateOrCreate(['ar_list_id' => $list_id,'ar_date'=> $ar_date], $request_data);
  • Related