Jane Doe
Jane Doe

Reputation: 302

Why is it when I take 3 array values it shows error but when I only show 1 value it works?

When I use var_dump($paid) it will show all the values
this is the code. If I use all 3 description, amount, and payment_type it will show an error that the amount is undefined. But if I use only 1 like for example I use only the description and erase the rest the code will work

$paid = array();
        foreach ( $user as $u ) :
            $paidDetail = \App\PaymentTransaction::where('user_id','=', $u->user_id)->get();
            if ($paidDetail->count()) :
                $paid[]['description'] = $paidDetail[0]->description;
                $paid[]['amount'] = $paidDetail[0]->amount;
                $paid[]['payment_type'] = $paidDetail[0]->payment_type;
            endif;  
        endforeach;

    return $paid;

this is for the view/blade to show the details in the frontend

{{ $paid['description'] }}
{{ $paid['amount'] }}
{{ $paid['payment_type'] }}

showing each 1 of them works but showing all of them at the same time will show an error saying that the 2nd value is undefined

Below is the var_dump($paid)

array(1) { ["description"]=> string(33) "Plan Subscription Payment for PRO" }
array(1) { ["amount"]=> float(350) }
array(1) { ["payment_type"]=> string(27) "Stripe Payment Subscription" }
array(1) { ["description"]=> string(38) "Test Plan Subscription Payment for PRO" }
array(1) { ["amount"]=> float(351) }
array(1) { ["payment_type"]=> string(27) "Stripe Payment Subscription" }

Upvotes: 0

Views: 44

Answers (2)

Webdesigner
Webdesigner

Reputation: 1982

Try this:

$paid = array();
$i=0;

foreach ( $user as $u ) :
    $paidDetail = \App\PaymentTransaction::where('user_id','=', $u->user_id)->get();
    if ($paidDetail->count()) :
        $paid[$i]['description'] = $paidDetail[0]->description;
        $paid[$i]['amount'] = $paidDetail[0]->amount;
        $paid[$i]['payment_type'] = $paidDetail[0]->payment_type;
        $i++;
    endif;
endforeach;

return $paid;

The main issue with you code is that you forgot to use a index on you array. Adding $i as an index makes sure that each user payment have his own index.

Note

Lopping thru an collection and doing a SQL QUERY for each user is not wrong but also not a good practice. Try to get both in one SQL Statment.

Upvotes: -1

Ravan
Ravan

Reputation: 1

It's just because,

Your foreach loop overwriting 0 Index Parameters and every time last record stores in Array.

And Executing query in every iteration of foreach loop may reduce your code performance.

You Should use laravel eloquent model and relationship for this issue.

https://laravel.com/docs/5.5/eloquent-relationships

Upvotes: 0

Related Questions