Djave
Djave

Reputation: 9329

Laravel where query using model's boolean function

I have a simple model function that returns either true or false, based on some logic that uses a number of columns of the model. So I can't just say where('quantity', '>', 10) or suchlike.

How would I create a where clause that can use this function? I have created a stripped back example of code that might appear in my model's file:

public function scopeWhereBoxNeeded($query)
{
    return $query->where(/* - - - - something here! - - - - */);
}

public function boxNeeded()
{
    
    if( $this->packets * $this->quantity > 21) // Potentially much more complex logic here
    {
        return true;
    }
    
    return false;
    
}

Now, in my controller I'd like to say Products::whereBoxNeeded()->get(). How do I do it?

Sidenote

At present I am returning all the models that match a broader query, then doing

$products = $products->filter(function($product)
{
    return $product->boxNeeded();
});

But this is breaking the pagination, as I use {{ $products->links() }} in the view, and I think after filtering the query this is removed.

Edit

The actual query I am doing is much more complicated:

public function boxNeeded()
{
    $now = Config::get('next_cut_off')->copy();
    $now->subMonths($this->month_joined);
    if(($now->month + 12 + $this->subscription_frequency) % $this->subscription_frequency == 0)
         return true;
     return false;
}

Upvotes: 0

Views: 4180

Answers (1)

Reza Shadman
Reza Shadman

Reputation: 617

You can use a custom where statement like:

public function scopeWhereBoxNeeded($query)
{
    return $query->whereRaw('(quantity * packets) > 10');
}

Upvotes: 1

Related Questions