skip to Main Content

I want to get records that are joined between this date period (2022-02-15, 2022-08-20)

$users = User::whereDate('start_at', '>=', $startDate)
            ->whereDate('end_at', '<=', $endDate)
            ->get();

4

Answers


  1. You can use the whereBetween Laravel function:

    $users = User::whereBetween('start_at', [ $startDate, $endDate])->get();
    

    Note $startDate and $endDate must be instance of Carbon.

    $startDate = new Carbon('paste_your_start_date')->format('Y-m-d')." 00:00:00";
    

    Update

    This would be one method to get data from two seperated columns. Example is not tested.

    $start_at = Carbon::createFromFormat('Y-m-d H', '2022-02-15 0')->toDateString();
    $end_at = Carbon::createFromFormat('Y-m-d H', '2022-08-20 0')->toDateString();
    
    $users = User::whereRaw("start_at <=  date('$start_at')")
                          ->whereRaw("end_at >=  date('$end_at')")
                          ->get();
    
    Login or Signup to reply.
  2. $_start_date = '2022-02-15';
    $_end_date ='2022-08-20';
    
    $users = User::where(function ($query) use ($_start_date, $_end_date) {
                        $query->where(function ($query) use ($_start_date, $_end_date) {
                            $query->whereRaw("start_date >= date('$_start_date')")
                                ->whereRaw("end_date <= date('$_end_date')");
                        })
                        ->orwhere(function ($query) use ($_start_date, $_end_date) {
                            $query->whereRaw("start_date <= date('$_start_date')")
                                ->whereRaw("end_date >= date('$_end_date')");
                        });
                    })->get();
    

    try above code this will also return between dates of start_date and end _date e.g below

    $_start_date = '2022-02-18';
    $_end_date ='2022-08-20';
    

    and also works with below dates e.g

    $_start_date = '2022-02-16';
    $_end_date ='2022-08-18';
    

    codes look like this in ide
    enter image description here

    Login or Signup to reply.
  3. Depends on what you need exactly

    User::whereDate('start_date', '>=', $startDate)->where('end_date', '<=', $endDate)->get();
    

    or

    User::whereDate('start_date', '<', $User)->whereDate('end_date', '>', $startDate)->get();
    
    Login or Signup to reply.
  4. I think you want to get the records that at least one day from start_date to end_date that exists between 2022-02-15 and 2022-08-20:

    $startDate = '2022-02-15';
    $endDate = '2022-08-20';
    $users = User::whereDate('start_at', '<=', $endDate) // where or whereDate also should work
        ->whereDate('end_at', '>=', $startDate)
        ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search