Majid Jalilian
Majid Jalilian

Reputation: 138

Laravel eloquent error expects parameter 1 to be string when trying to use sum

I used this query:

Product::whereId($item->id)->sum(function ($row) {
                return $row->quantity * ($row->variable ?? 1);
            });

But I got this error:

production.ERROR: stripos() expects parameter 1 to be string, object given

I want to get the result of $row->quantity * $row->variable as the sum, but some of $row->variable are null so I used ($row->variable ?? 1).

Upvotes: 1

Views: 507

Answers (4)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

I would suggest to perform such sum operation directly at database layer by doing some conditional aggregation

Product::whereId($item->id)
       ->sum(\DB::raw('quantity * (case when variable > 0 then variable else 1 end)'));

There are 2 main benefits of above approach

  • Keep your logic/code as simple as it should be so there is no need to fetch all rows in memory (codebase) whether your data set for given condition is small or large when you can directly fetch it from database server which a very common operation for databases to handle.
  • No extra loop and calculation is required while using collection helper method

Upvotes: 1

Mohammad Akbari
Mohammad Akbari

Reputation: 446

Run sum function on a collection if your collection is small is fine

but if you have a huge collection, for example say you have 2000 items in it, then calculate the sum in mysql will be a good choice

in your code, you first get the result from DB and then run the sum operation of collection in php not in mysql

but the result is same

until you have to face the big collection do not worry about it

Upvotes: 0

Majid Jalilian
Majid Jalilian

Reputation: 138

I used get() to get collection before sum and my problem solved.

so I changed my code to this:

Product::whereId($item->id)->get()->sum(function ($row) {
                return $row->quantity * ($row->variable ?? 1);
});

Upvotes: 0

Mohammad Akbari
Mohammad Akbari

Reputation: 446

Yes, it throws exception because you must use string instead of function(closure)

use this for example

Product::selectRaw("sum(quantity * variable)")->whereId($item->id)->get();

Upvotes: 1

Related Questions