8

This is the code in my Product model to get the minimum price value (one product can have multiple price)

public function getLowestAttribute ()
{
    return $this->prices->min('price');
}

But it will return NULL rather than the smallest integer if there is a NULL.

Basically I want to achieve this:

[1, NULL, 2] returns 1

[1, NULL, 0] returns 0

Any suggestion would be appreciated.

2
  • And what if the values are NULL only, something like as [NULL, NULL] Jun 11, 2016 at 9:07
  • @Uchiha it's impossible in my case. Because the product needs to have at least one non-null price before it can be added into the database.
    – Harrison
    Jun 11, 2016 at 9:18

5 Answers 5

10

I found filter, and it works now.

public function getLowestAttribute ()
{
    $prices = $this->prices->filter(function ($item) {
        return !is_null($item->price);
    });

    return $prices->min('price');
}
1
  • FWIW, as of Laravel 5.1, it is possible to not provide a callback to the filter function - this will remove any items that equal false Mar 25, 2019 at 16:14
7

Have you tried maybe

public function getLowestAttribute ()
{
    return $this->prices->where('price','>=',0)->min('price');
}
5

A fix to the KuKeC answer would be

public function getLowestAttribute()
{
    return $this->prices->where('price', '!==', null)->min('price');
}
0

Previous 2 solutions provided did not work for me in Laravel 6.2 neither I want filter unless I have to

I used per documentation https://laravel.com/docs/6.x/queries#where-clauses

… ->whereNotNull('price')-> …

Although in my specific situation I needed NULLs so I actually used

… ->whereNull('price')-> …
0

Try this answer, It works for me

public function getLowestAttribute ()
{
    return $this->prices->whereNotNull('price')->min('price');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.