Jane Doe Jane Doe - 1 year ago 78
PHP Question

how to do "if firstOrNew then increment"?

I am currently building a website with a table that counts how many times the users used the coupon.

This is the line that I used to increment. It worked well but it increments every time the page was refreshed.


I wanted this to increment only once even though the page was refreshed multiple times. Please help me :)

Answer Source

You can use a session for that. Here's an example (using Laravels global session helper):

if (!session()->has('coupon_used')) {
    session()->put('coupon_used', true);

This first checks if the session exists. If it doesn't, it runs the code and sets the session. The second time the page is loaded, the session will be set and the code won't run.


The above code only allows for one coupon per user session, regardless if they are different ID's. If you want to add the same functionality for different coupons (getting it to be able to increment once per coupon id), then you can do this:

if (!session()->has('coupon_' . $coupon[0]->coupon_id)) {
    session()->put('coupon_' . $coupon[0]->coupon_id, true);

This does the same thing, but sets a session for just that coupon ID (since it dynamically creates the session name to have the ID appended).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download