How to prevent duplicate records in a table?

I did a little research in the Internet, in the documentation searched, but have found absolutely nothing.

I wrote subscribe to your categories AJAX method.

Send the id to the server, but already there is recorded in the table user_id and category_id.

The fact is that if, for some reason, to go two times an AJAX request, the table will be written two times the same. And that's too bad.

Example:

if ($request->post('category_id')) {

 $user_category = new a 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 the record, and if it is not(exactly the same), then record a new record ?

Please help in solving the problem...

Thanks in advance.
June 5th 19 at 21:03
2 answers
June 5th 19 at 21:05
Solution
There is a method firstOrNew() example from docks:
// To Retrieve by name, or instantiate...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

// To 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...
June 5th 19 at 21:07
Solution
$user_category = a usercategory::where('user_id', Auth::user()['id'])
 ->where('category_id', $request->post('category_id'))
->first();
if(!$a usercategory) {
 $user_category = new a 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']);
}
}
Thank you very much! It became clear now. - terry.Hagenes33 commented on June 5th 19 at 21:10

Find more questions by tags Laravel