1

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?

2 Answers 2

3

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 https://laravel.com/docs/5.2/queries#conditional-statements

UPDATE:

Any expression that you can be used inside an if call can be used as the first argument of when

An example :

->when($fromDate && $toDate, function($query) use ($fromDate, $toDate) {
    return $query->whereBetween('CompletedDate', array($fromDate, $toDate));
})
Sign up to request clarification or add additional context in comments.

1 Comment

what if the where query is a whereBetween Query. ->whereBetween('CompletedDate', array($fromDate, $toDate)). Thanks
0

You can use orWhere():

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

Comments

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.