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

jsvaryuna's avatar

Multiple condition for query

Hi,

Suppose I have a table called Book and I'd like to allows the users to filter the content based on:

startWith (first letter of the book)

Genre

sortOrder(recently added,most popular(view count), releasedate,rating...)

searchString (where title = %user_string%)

What is the best way to build this query without so many if/else

0 likes
4 replies
jsvaryuna's avatar

yes saw that, but it seemed complicated when involving like 3 conditions in the same time

jlrdw's avatar
jlrdw
Best Answer
Level 75

@jsvaryuna there is nothing wrong with if's, just my opinion.

Just example



        $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);
        etc
2 likes

Please or to participate in this conversation.