whereBetween Dates in laravel 4 eloquent

33,355

Solution 1

DB::table(sp_price)
     ->whereBetween('from_date',array('2014-08-15','2014-08-18'))
     ->orWhereBetween('to_date',array('2014-08-15','2014-08-15'))
     ->get();

maybe you can try this

Solution 2

  $count =  TokenLog::whereBetween(DB::raw('date(created_at)'), [$start_date, $end_date])->get();

Solution 3

In your example, you're checking both from_date and to_date for the same range of dates...if this will always be the case, you can make this query a bit more "eloquent":

In the SpPrice.php model:

public function getPriceByDate($fromDate, $toDate)
{
    $range = [$fromDate, $toDate];
    return $this
        ->whereBetween('from_date', $range)
        ->orwhereBetween('to_date', $range)
        ->get();
}

Then, to call this method from a controller:

    $prices = new SpPrice;
    $price = $prices->getPriceByDate('2014-08-15', '2014-09-18');
Share:
33,355
Md. Sahadat Hossain
Author by

Md. Sahadat Hossain

profile for Md. Sahadat Hossain at Stack Overflow, Q&A for professional and enthusiast programmers http://stackoverflow.com/users/flair/2738927.png Careers 2.0 Profile

Updated on July 25, 2022

Comments

  • Md. Sahadat Hossain
    Md. Sahadat Hossain almost 2 years

    I have a query like that

    SELECT * FROM `sp_price` WHERE (`from_date` between '2014-08-15' and '2014-09-18') || (`to_date` between '2014-08-15' and '2014-09-18')
    

    Now how I can convert this query in laravel 4. I use Eloquent

  • 89n3ur0n
    89n3ur0n over 8 years
    how can I build this select * from calendar_schedules as cs where 1446377416 between cs.from_booking_date and cs.to_booking_date;
  • 89n3ur0n
    89n3ur0n over 8 years
    Here is what that works : $schedule = DB::table('calendar_schedules') ->whereRaw('(? between from_booking_date` and to_booking_date) OR (? between from_booking_date and to_booking_date)',[$request->input('startDate'),$request->in‌​put('endDate')]) ->first();`