Laravel API prevent multiple insert/update
P粉864594965
P粉864594965 2024-03-27 11:51:51
0
1
485

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粉864594965
P粉864594965

reply all(1)
P粉775723722

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, []);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template