user3653474
user3653474

Reputation: 3854

Compare date time in Laravel eloquent

I have start and end date time column in database

start_date             end_date             contact
2021-01-25 17:30:00    2021-01-25 20:30:00   xxxxxxxxx
2021-01-27 17:30:00    2021-01-28 19:30:00   xxxxxxxxx

Now i'm trying to get records which exists between these two date time, it should match mobile number also.I'm using below query but it is not filtering record

   $date = date('Y-m-d H:i:s', strtotime($request->date));
   $contact_number=$request->contact_number;

$event=Event::where(function ($query)use($date,$contact_number){
    $query->where('start_date', '>=', $date)->where('end_date', '<=', $date);})->where('contact',$contact_number)->paginate(5);  

Upvotes: 0

Views: 13000

Answers (3)

Azahar Alam
Azahar Alam

Reputation: 741

Try this:

$date = Carbon\Carbon::parse($request->date)->format('Y-m-d H:i:s');
$contact_number=$request->contact_number;

$event=Event::where(function ($query)use($date,$contact_number){
    $query->where('start_date', '<=', $date)->where('end_date', '>=', $date);})->where('contact',$contact_number)->paginate(5);

Upvotes: 0

Cl&#233;ment Baconnier
Cl&#233;ment Baconnier

Reputation: 6058

You have to invert the >= and <= signs

$date = date('Y-m-d H:i:s', strtotime($request->date));
$contact_number = $request->contact_number;

$event = Event::where(function ($query) use ($date, $contact_number){
        $query->where('start_date', '<=', $date)
              ->where('end_date', '>=', $date);
    })
    ->where('contact',$contact_number)
    ->paginate(5); 

Upvotes: 3

Wajid
Wajid

Reputation: 593

Laravel 4+ offers you these methods: whereDay(), whereMonth(), whereYear()  and whereDate() .




Here are some ways to make the comparison :

->where('date', '<=', '2014-07-10 23:59:59')

->where('date', '<', '2014-07-11')

// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');

->where('date', '<', $dayAfter)

Upvotes: 0

Related Questions