skip to Main Content

Data is not coming when comparing current time between 2 times to fetch data in Laravel. Both times are saved in the database as timestamp and in query also I am using timestamp. Below is the code i wrote:-

$current_date = strtotime(date('d-m-Y H:i:s'));
        
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get();

"time_from" and "time_to" both timestamps are saved in bigint format in database. I entered timestamp using search option in direct database also still data did not come. Can someone please tell me where i am making mistake.

5

Answers


  1. You not describe what database you use. But maybe you can change to Y-m-d H:i:s format:

    $current_date = strtotime(date('Y-m-d H:i:s'));
    

    but strtotime is return int not bigint.

    Login or Signup to reply.
  2. I hope I will help you
    firstly You must cast the date in Model MachineBooking

    protected $casts = ['time_from' => 'datetime:Y-m-d H:i:s',time_to =>'datetime:Y-m-d H:i:s'];
    

    secondly
    cast current date with same format of time_from and time_to

    $current_date = strtotime(date('Y-m-d H:i:s'));
    
    Login or Signup to reply.
  3. Please change your code with:

    $current_date = strtotime(date('Y-m-d H:i:s'));
    
    Login or Signup to reply.
  4. time_from and time_to are formatted date not a int . But your $current_date is int with using strtotime method
    Just take strtotime method:

    $current_date =date('d-m-Y H:i:s'); 
    $bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get()
    
    Login or Signup to reply.
  5. I think you should swap the time_from to <= and time_to to >, and try

    $bookings = MachineBooking::with('userDetail')
        ->where('machine_id', $machine_id)
        ->where('time_from', '<=', $current_date) # changed
        ->where('time_to', '>', $current_date) # changed
        ->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search