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

richard's avatar

Multiple WHERE conditions in SQL query

I have students details in my database.

firstname
lastname
DOB
gender
status (Active, Not Active)
fee_paid

I also have a search form on the views that I want to use to search students based on different conditions.

For example, I may want to search these

  1. All female students who were born between date1 to date2 and have paid x amount of fees.
  2. All students called Ali who have paid x amount of fees.
  3. All Active students who have not paid any fees.

My question, how can I simply check, if a field is set, then use it in a query, otherwise don't include it in the query. Also for DOB, search is by date range.

0 likes
7 replies
TerrePorter's avatar

Maybe something like this,

// make a base query
$query = Model::all();

// check if form has value
if (Input::has('firstname')) {
    // modify the query
    $query->where('firstname', Input::has('firstname')); // only if firstname = input_value
}

// pull the query
$result = $query->get();
Ricardo's avatar

@richard

$query = Student::query();

if ($gender = request('gender')){
    $query->where('gender', $gender);
}

$student = $query->get();
1 like
richard's avatar

Thanks @TerrePorter, but when the user doesn't specify the search the criteria, I get Missing argument 1 for Illuminate\Support\Collection::get() error

zachleigh's avatar

You could also do something like this:

$input = $request->all();

$query = Student::query();

foreach ($input as $key => $value) {
    $method = 'query' . ucfirst($key);

    if (method_exists($this, $method)) {
        $this->{$method}($query, $value);
    }
}

$students = $query->get();

And then have different methods for each query type:

public function queryGender($query, $gender)
{
    $query->where('gender', $gender);
}

It might be a little cleaner than having a huge conditional to check for all the input values and you could reuse the code in the query methods for other things.

1 like
jekinney's avatar

@zachleigh I do the same thing!!! Well, very close too, I empty check the $value and if not chain on a where().

Please or to participate in this conversation.