Answer the question
In order to leave comments, you need to log in
How to disable duplicate records in a table?
I searched a little in the Internet, looked in the documentation, but did not find what I needed.
I wrote the ability to subscribe to categories using the AJAX method.
I send the id to the server, and there the user_id and category_id are already written to the table.
The fact is that if, for some reason, an AJAX request is sent twice, then the same thing will be written twice in the table. And it's very bad.
Example:
if ($request->post('category_id')) {
$user_category = new UserCategory();
$user_category->user_id = Auth::user()['id'];
$user_category->category_id = $request->post('category_id');
if ($user_category->save()) {
return response()->json(['response' => 'Category success']);
}
}
Answer the question
In order to leave comments, you need to log in
There is a firstOrNew() method, an example from the docs:
// Retrieve by name, or instantiate...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
// Retrieve by name, or instantiate with the name and delayed attributes...
$flight = App\Flight::firstOrNew(
['name' => 'Flight 10'], ['delayed' => 1]
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question