Eloquent between two dates from database

i am trying to get an object from a database where the schema is

timestamp period_starts_at timestamp period_ends_at

and i want to get all the first record that today is with in the period_start or period_end can anyone help how might would i express it in laravel.

pulic function current(){
   $dt = Carbon::now();
        $current = Connection::
            where('user_id',$this->user_id)
            ->where('status','active')
            ->where('period_starts_at','>=',$dt)
            ->where('period_ends_at','<=',$dt)
            ->first();
        return $current;
}
threeel
threeel
  • 1 year ago

use whereBetween

http://laravel.com/docs/4.2/queries

i tried but i seem to fail to implement it can you explain how? the whereBetween expects an array of dates that i already have which in my case is part of the record that i want to retrieve...

kunalthool said:

use whereBetween

http://laravel.com/docs/4.2/queries

elite123
Solution

Are your operators the right way round?

->where('period_starts_at','<=',$dt)
->where('period_ends_at','>=',$dt)
->first();

Oh i got the error you cant get the results.

No here is the solution

public function current(){ $from = date('Y-m-d' . '00:00:00', time()); $to = date('Y-m-d' . '24:60:60', time());

    $current = Connection::
        where('user_id',$this->user_id)
        ->where('status','active')
      ->whereBetween('created_at', array($from, $to))->first();

return $current; }

oops :)

public function current(){
 $from = date('Y-m-d' . ' 00:00:00', time()); //need a space after dates.
 $to = date('Y-m-d' . ' 24:60:60', time());

   $current = Connection::
      where('user_id',$this->user_id)
        ->where('status','active')
        ->whereBetween('created_at', array($from, $to))->first();

    return $current;
  }

We can get records between two dates laravel5 with using Eloquent "whereBetween" method. Here #sample function to get posts between two dates from database

public function getPosts(){ 
  $fromDate = date('Y-m-d' . ' 00:00:00', time()); 
  $toDate = date('Y-m-d' . ' 22:00:40', time()); 
  $posts = POST:: where('user_id',$this->user_id) ->where('status',1)->whereBetween('posted_on', [$fromDate, $toDate])->get(); 
 return $posts; 
} 

Read more from https://laravel-interview-questions.blogspot.in/2017/03/getting-records-between-two-date-in.html