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

juanca3993's avatar

whereBetween when date is null

i have one problem when i want to build one query and date from/to are null. I dont get records. If from and to are null with this sentence i dont have all records. I do not get any results. or if from is empty or to is empty is the same way -> I do not get any results.

$model = model::whereBetween('date',[from,to])->get()

i created this way... but i want to know if there is a easy way to make this:


$whereFrom = !empty(request()->from) ? "`date` >  ".request()->from : '';
$whereTo = !empty(request()->to) ? "`date` <  ".request()->to : '';
$conditional = !empty($whereFrom) && !empty($whereTo) ? ' and ' : '';
$model = model::where(function($query) use ($whereFrom,$conditional,$whereTo){
            if(!empty($whereFrom) || !empty($whereTo)){
                $query->whereRaw($whereFrom.$conditional.$whereTo);
            }
        })->where(more_information )->get()

Thanks !!!!

0 likes
12 replies
juanca3993's avatar

@MichalOravec Yes... but one little think: when you put the clause => the query has one error

select count(*) as aggregate from `m_special_events` where `date` = '=>' and `event_type` like '%%'

but if you put this clause >= It is working... could you test and edit this with this little change ? Thanks

juanca3993's avatar

@MichalOravec

        $from = request()->from;
        $to = request()->to; 
        $event_type = request()->event_type;
        $mSpecialEvents = MSpecialEvent::when(request()->from, function ($query, $from) {
            $query->where('date', '=>', $from);
        })->when(request()->to, function ($query, $to) {
            $query->where('date', '<=', $to);
        })->where('event_type','like','%'.request()->event_type.'%')->orderBy('id','desc')->paginate();

Please or to participate in this conversation.