Home > Enterprise >  Laravel API prevent multiple insert/update
Laravel API prevent multiple insert/update

Time:06-06

I have a method for sending a notice on my NoticeController.

The issue was it cannot detect whether the api endpoint was called multiple times (such as double form submission from client side) or if the notice was already sent to the student. It causes duplicate records on the database, when I need it to only insert once.

 public function sendStudentNotice(Request $request, Registrant $registrant){

        $validated = $request->validate([
            'type' => 'required|in:success,error,warning,info',
            'message' => 'required|string'
        ]);

        //This is inserting new record each call
        $registrant->enrollmentLogs()->create($validated);

        return response()->json(['message' => 'A notice has been sent successfully!']);
    }

It would be better if I can protect all store and update methods on my controller to prevent this kind of issue.

CodePudding user response:

You can use ->firstOrCreate([],[]) method instead of create, and it'll first check the database for a record for all the fields given in the first argument, and then if it doesn't find it one it'll create one along with the data in the second argument.

example for you:

 $registrant->enrollmentLogs()->firstOrCreate($validated, []);

CodePudding user response:

Make changes as per below

$registrant->enrollmentLogs()->create($validated); replace this line with below code

$registrant->enrollmentLogs()->firstOrCreate([
            'type' => $request->input('type'),
            'message' => $request->input('message')
    ], $request->only('type', 'message'));
  • Related