Matt Matt - 1 year ago 85
SQL Question

Where clause with a blank variable Laravel

I use GET, to collect a variable :

$subid = $_GET['subid'];

In my DB Query i have the following :

->where('subID', '=', $subid)

Now if the variable $subid is blank , the result returns no information. How do i specify in the query that if the variable $subid is blank or empty, return all results?

Answer Source

You can use when.

->when($subid, function ($query) use ($subid) {
    return $query->where('subID', '=', $subid);

If $subid is false the where condition won't be applied to the query.

Check out the doc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download