0

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?

Dalama
  • 19
  • 5

2 Answers2

0

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):

  • catch the Exception thrown by your database: if it relates to a duplicate primary key then you could handle the case accordingly (ie perhaps ignore it and continue as if the INSERT operation had succeeded)
  • perform a SELECT operation on your database, just before you attempt to save the value. If there is already a value there, then use UPDATE rather than INSERT
  • some databases (eg MySQL) have extensions to standard SQL that allow you to do things like REPLACE INTO or INSERT IGNORE: you could use one of these instead of the standard INSERT statement
Rob Eyre
  • 717
  • 7
  • Thank you, from docs the POST method not idempotent. Therefore should I do this idempotent? Why just not return a exception message for the user? – Dalama Nov 08 '22 at 20:51
  • here you have an answer which implement @Rob Eyre solution: https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server – Lenny4 Nov 08 '22 at 20:52
0

You can use firstOrCreate() or updateOrCreate() methods of laravel query builder to prevent this exception and keep your method idempotent

Vlad
  • 871
  • 1
  • 8