Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alex29's avatar

Run a different query if column value equals something else

I was wondering if there was a way to do this. For example, I have a properties table with a price and rental_frequency column. The rental_frequency column's values can either be daily, weekly, monthly or yearly. Would it be possible to do a different query on each row depending on their rental_frenquency value? Something like this maybe:

  1. If rental_frequency is daily then retrieve the rows with the price around 2000
  2. AND If rental_frequency is monthly then retrieve the rows with the price around 20000
  3. AND If rental_frequency is yearly then retrieve the rows with the price around 2000000

I understand this can be achieved by mapping the collection but I wanted to do it from the query level so as not to slow down the program. Thanks.

0 likes
4 replies
alex29's avatar

Sorry, but how exactly? I'm aware of query scopes but I'm not quite sure how I can get Eloquent or MySQL to do if column value === 'rental' then do this query otherwise do this query

jlrdw's avatar

@alex29 Of course you have to use some if's, an example I have:

        $query = Dog::where('dogname', 'like', $dogsch);
        if ($aval == "n") {
            $query->where('adopted', '=', 1);
        } else if ($aval == "y") {
            $query->where('adopted', '=', 0);
        }
        $dogs = $query->orderBy('lastedit', 'DESC')->paginate(5);

        $params = array('psch' => $dogsearch, 'aval' => $aval);

Note the if ($aval == "n") {, so if your conditionals.

Also you can look at the when:

https://laraveldaily.com/less-know-way-conditional-queries/

Also, look into a query grouping by price range is possible.

Snapey's avatar

your question is not clear enough to answer. Try providing more context

and way do you mean by 'around' ? queries cannot work with vague values

Please or to participate in this conversation.