Melek Yilmaz
Melek Yilmaz

Reputation: 519

Laravel collections

This is my code :

$selectedInvoices = $input['invoice'];

        $invoices = collect([]);
        foreach ($selectedInvoices as $invoice) {
          $merged = $invoices->merge([Invoice::find(Invoice::getPrivateId($invoice))]);
        }
        $merged->all();

        $totalAmount = 0;

        foreach ($merged as $invoice)
        {
            $totalAmount = $totalAmount + $invoice->balance;
        }

My problem is $invoices and $merged values are not the instances of the invoices which have a selected id ... wan any one help me please ?

Upvotes: 0

Views: 54

Answers (1)

Adam Kelso
Adam Kelso

Reputation: 391

I'm not sure what your getPrivateId method is, but guessing it's something specific to your application.

Try something like this instead:

// This is assuming your $input['invoice'] is an array
$privateIds = collect($input['invoice'])->map(function($item) {
  return Invoice::getPrivateId($item);
});

// Replace 'id' with whatever column name you're using as an ID.
$invoices = Invoice::whereIn('id', $privateIds->all())->get();

$totalAmount = $invoices->sum('balance');

By default, Laravel returns a collection when you make an Eloquent query. The collection contains the invoice instances.

Upvotes: 1

Related Questions