Jane Doe Jane Doe - 28 days ago 11
PHP Question

The code can only see the first one on the array

Can anyone tell me what's lacking in this code?

I wanted it to increment all of the coupons on the array but it only increments the first one

This is the controller

public function paidCount($user_id) {
$meta = \App\EventBookingsMeta::where('user_id', '=', $user_id)->where('meta_key', 'LIKE', 'used_coupons')->value('meta_value');
if ( $meta ) {
$decode = json_decode( $meta );
if ( count( $decode ) > 0 ) {
foreach( $decode as $coupon) {
return \App\Coupon::find($coupon)->increment('no_paid');
}
}
}
}


this is what my "meta table" looks like

user_id meta_key meta_value
1 used_coupons [3,5,9]
2 used_coupons [7, 8]


and this is the "coupons table"

coupon_id no_paid
3 1
5 0
7 1
8 0
9 0


Only the 3 and 7 were incremented

Answer

Remove the return statement from your foreach loop. Calling a return will break out of paidCount on the first iteration.

Note the removed return in the example below.

public function paidCount($user_id) {
   $meta = \App\EventBookingsMeta::where('user_id', '=', $user_id)->where('meta_key', 'LIKE', 'used_coupons')->value('meta_value');
      if ( $meta ) {
        $decode = json_decode( $meta );
        if ( count( $decode ) > 0 ) {
            foreach( $decode as $coupon) {
                \App\Coupon::find($coupon)->increment('no_paid');
            }
        }
    }
  }