J
J
Jedi2018-05-19 03:28:18
Laravel
Jedi, 2018-05-19 03:28:18

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']);
            }
        }

How can I check first for the existence of an entry, and if it does not exist (exactly the same), then write a new entry?
I ask you to help in solving the problem ...
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yan-s, 2018-05-19
@PHPjedi

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]
);

https://laravel.com/docs/5.6/eloquent#insert-updat...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question