Jane Doe Jane Doe - 1 month ago 11
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.

\App\Coupon::where('coupon_id','=',$coupon[0]->coupon_id)->increment('no_paid');


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

Answer

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

if (!session()->has('coupon_used')) {
    \App\Coupon::where('coupon_id','=',$coupon[0]->coupon_id)->increment('no_paid');
    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.

Alternatively

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)) {
    \App\Coupon::where('coupon_id','=',$coupon[0]->coupon_id)->increment('no_paid');
    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).

Comments