4 years ago

ForEach on Collection from Model returns empty

Posted 4 years ago by jsrosas

Hiya all, once again with probably a newbie question lol. I'd appreciate your help. I have some users that are making payments into Stripe and I am storing the amounts they are paying in a table. I have a relationship of User::hasmany, and UserPaymphpent::belongsto. So when I have

    public function charges(){
        return $this->hasMany('App\UserPayment');

I get a collection of payments done by that Use. Now I need to iterate through each payment and sum up all the amounts they payed. When I just simply return the collection I get on blade the following:

[{"id":1,"member_id":"44","stripe_id":"cus_00000000000000","email":"[email protected]","amount":50000,"amount_decimal":0,"amount_refunded":0,"invoice_number":null,"date_created":1326853478,"created_at":"2016-06-28 20:12:35","updated_at":"2016-06-28 20:12:35"},{"id":2,"member_id":"44","stripe_id":"cus_00000000000000","email":"[email protected]","amount":50000,"amount_decimal":0,"amount_refunded":0,"invoice_number":null,"date_created":1326853478,"created_at":"2016-06-28 20:12:35","updated_at":"2016-06-28 20:12:35"},{"id":3,"member_id":"44","stripe_id":"cus_8iuCeLKHZGxWQD","email":"[email protected]","amount":50000,"amount_decimal":0,"amount_refunded":0,"invoice_number":null,"date_created":1467144078,"created_at":"2016-06-28 21:10:19","updated_at":"2016-06-28 21:10:19"}]

So I thought I could do foreach and just += each $payment->amount. But the for each is not going through them. Just returns blank, even If I just simply do inside the foreach($payments as $pay){echo "one payment";} I get blank. So I tried json_decode on the $payments collection and I get:

json_decode() expects parameter 1 to be string, object given How can I iterate through each payment and sum up the amounts? Thank you in advance.

Please sign in or create an account to participate in this conversation.