0

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;
}

1 Answer 1

1

You can use a custom where statement like:

public function scopeWhereBoxNeeded($query)
{
    return $query->whereRaw('(quantity * packets) > 10');
}
Sign up to request clarification or add additional context in comments.

2 Comments

I really need it to work via a function, as I'll be using a much more complicated query (see edit). My question is how can I use the result of a function that returns true / false in a where statement
As I understood you want to use a Php logic inside a Sql statement, I think the best way is to include the logic inside the sql statement. The result of your function depends on Sql data which is not present.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.