Here is a Rest Api method that sets the user rating. The database table contains the composite primary key: user_id
+ rate_id
.
When user tries to set the same rating the framework throws an exception. I catch it and return response.
How to handle such these cases and make the method idempotent?
2
Answers
Without more detail (and a code sample), it’s difficult to advise. However, in high-level, general terms you could do one of the following (presuming you are using a relational database):
SELECT
operation on your database, just before you attempt to save the value. If there is already a value there, then useUPDATE
rather thanINSERT
REPLACE INTO
orINSERT IGNORE
: you could use one of these instead of the standardINSERT
statementYou can use firstOrCreate() or updateOrCreate() methods of laravel query builder to prevent this exception and keep your method idempotent