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

saadaan's avatar

Running WHEN condition for query

Hi,

I am trying to run a WHEN condition in some code in blade. It works fine in blade when the variable is coming via REQUEST object. However, it's not working in blade when I try to replace the request variable with a custom variable. The documentation says if the first condition is true, it should work. However, it's not working, and the query is being executed without the WHEN conditions below every time.

//$start_date = '2019-10-01';
//$end_date = '2019-10-22';

$c = DB::table('campaigns')->where('start_time','like', $mm.'%')                                
         ->when($start_date!=='', function ($query, $start_date) {
             return $query->where('start_time', '>=', $start_date.'%');
          })
         ->when($end_date!=='', function ($query, $end_date) {
             return $query->where('start_time', '<=', $end_date.' 23:59:59');
          })
         ->get();

Can someone please guide?

Thanks, Saad

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

An empty string results in false and a string with data results in true. But you are not passing the date right.. so try this instead:

$c = DB::table('campaigns')->where('start_time','like', $mm.'%')                                
    ->when($start_date, function ($query) use ($start_date) {
        return $query->where('start_time', '>=', $start_date.'%');
    })
    ->when($end_date, function ($query) use ($end_date) {
        return $query->where('start_time', '<=', $end_date.' 23:59:59');
    })
->get();
Sinnbeck's avatar

How are you setting your variables in blade?

Also I would recommend moving this sort of logic into a controller or model.

saadaan's avatar

I am pushing the variable to blade via controller.

I know it has to go into controller ultimately, but I have to make the values working first for a visualization graph successfully, before I write additional logic to control it via controller.

Please or to participate in this conversation.