Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent how to get the minimum value that is not NULL?

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.

like image 905
Harrison Avatar asked Jun 11 '16 08:06

Harrison


3 Answers

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');
}
like image 96
Harrison Avatar answered Oct 06 '22 18:10

Harrison


Have you tried maybe

public function getLowestAttribute ()
{
    return $this->prices->where('price','>=',0)->min('price');
}
like image 33
KuKeC Avatar answered Oct 06 '22 17:10

KuKeC


A fix to the KuKeC answer would be

public function getLowestAttribute()
{
    return $this->prices->where('price', '!==', null)->min('price');
}
like image 24
Efigie Avatar answered Oct 06 '22 19:10

Efigie