search

Home  >  Q&A  >  body text

Laravel API prevent multiple insert/update

I have a method that sends notifications on my NoticeController.

The problem is that it cannot detect if the API endpoint is called multiple times (e.g. double form submission from client) or if a notification is sent to the student. It results in duplicate records on the database when I only need to 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 could protect all store and update methods on the controller to prevent such problems.

P粉864594965P粉864594965244 days ago478

reply all(1)I'll reply

  • P粉775723722

    P粉7757237222024-03-28 09:30:41

    You can use ->firstOrCreate([],[]) method instead of create, it will first check the records of all the fields given in the first parameter in the database, and then, if It doesn't find it, it creates one along with the data in the second parameter.

    Example for you:

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

    reply
    0
  • Cancelreply