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

shami003's avatar

Query inputs in from_date and to_date

I have two inputs in form from_date and to_date,

I also have two fields in database from_date and to_date,

I want to query the records using input from_date and to_date, I want to query data from database where the inputs are in between from_date and to_date of database.

$from_date = $request->input('from_date');
$to_date = $request->input('to_date');

$absentees = AbsenteeRecord::whereIn('student_id', $student_ids)->orWhereDate('from_date', '<=', $from_date)->OrwhereDate('to_date', '>=', $to_date)->get();
0 likes
8 replies
SilenceBringer's avatar

@shami003 try this

$absentees = AbsenteeRecord::whereIn('student_id', $student_ids)
    ->whereDate('from_date', '>=', $from_date)
    ->whereDate('to_date', '<=', $to_date)
    ->get();

be sure your $from_date and $to_date have appropriate format

if sometimes you have just 1 value (for example, $from_date, but $end_date is null) use this https://laravel.com/docs/8.x/queries#conditional-clauses

$absentees = AbsenteeRecord::whereIn('student_id', $student_ids)
     ->when($from_date, function ($query, $from_date) {
         return $query->whereDate('from_date', '>=', $from_date)
    })
     ->when($to_date, function ($query, $to_date) {
         return $query->whereDate('to_date', '>=', $to_date)
    })
    ->get();
shami003's avatar

I want to get record if only one of the input is in between from and to. I am doing this for attendance records generation

SilenceBringer's avatar

@shami003 this way:

$absentees = AbsenteeRecord::whereIn('student_id', $student_ids)
    ->where(function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '>=', $from_date)
            ->orWhereDate('to_date', '<=', $to_date)
    })
    ->get();
SilenceBringer's avatar

@shami003 because I forgot to put semicolon

$absentees = AbsenteeRecord::whereIn('student_id', $student_ids)
    ->where(function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '>=', $from_date)
            ->orWhereDate('to_date', '<=', $to_date);
    })
    ->get();
shami003's avatar

@silencebringer I think the operators are opposite. The inputs between doesn't work.

My data in database from_date = 2021-06-06 to_date = 2021-06-10

My inputs $from_date = 2021-06-07 $to_date = 2021-06-07

But this works when my inputs are

Inputs $from_date = 2021-06-06 $to_date = 2021-06-09

Or

Inputs $from_date = 2021-06-04 $to_date = 2021-06-09

Can we use whereBetween?

shami003's avatar

The format is same, I have checked the records coming but I want that only one of them is in between from and to

Please or to participate in this conversation.