Home > Back-end >  How to get the records of a day in 30 minute intervals in laravel eloquent
How to get the records of a day in 30 minute intervals in laravel eloquent

Time:09-22

i have question about larave eloquent for get rows of day in the form of (n)min for example 30 min

From 8:00:00 To 8:29:59 :
col1 - col2 - col3
col1 - col2 - col3
...
From 8:30:00 To 8:59:59 :
col1 - col2 - col3
col1 - col2 - col3
...
...
...
From 23:30:00 To 23:59:59 :
col1 - col2 - col3
col1 - col2 - col3

I actually need to split a day into 30 minute intervals with laravel qeloquent

is there way to do this without loop and mapping with php for better performance in big tables ? if there is not whats is best way to get result like this . tnx

CodePudding user response:

You may follow the steps like:

  • Create an artisan command
  • Register a cron job via crontab

N.B: Have a look on the topic Task Scheduling on Laravel documentation.

CodePudding user response:

I found a solution

I made an array of the required time intervals, then made a loop on this array Then each key of the array, a query to the database

Then I combined the outputs

the code of rage maker in my trait

<?php
namespace App\Traits;
trait HoursRange {
protected function range($lower = 0, $upper = 86400, $step = 3600, $format = '')
{
    $times = array();

    if ( empty( $format ) ) {
        $format = 'g:i a';
    }

    foreach ( range( $lower, $upper, $step ) as $increment ) {
        $increment = gmdate( 'H:i', $increment );

        list( $hour, $minutes ) = explode( ':', $increment );

        $date = new \DateTime( $hour . ':' . $minutes );

        $times[(string) $increment] = $date->format( $format );
    }

    return $times;
 }
}

and call like this for make range

return hoursRange($lower = 28800, $upper = 86400, $step = 1800, $format = 'H:i:s');

this output is this :

{
  08:00: "08:00:00",
  08:30: "08:30:00",
  09:00: "09:00:00",
  09:30: "09:30:00",
  10:00: "10:00:00",
  10:30: "10:30:00",
  11:00: "11:00:00",
  11:30: "11:30:00",
  12:00: "12:00:00",
  12:30: "12:30:00",
  13:00: "13:00:00",
  13:30: "13:30:00",
  14:00: "14:00:00",
  14:30: "14:30:00",
  15:00: "15:00:00",
  15:30: "15:30:00",
  16:00: "16:00:00",
  16:30: "16:30:00",
  17:00: "17:00:00",
  17:30: "17:30:00",
  18:00: "18:00:00",
  18:30: "18:30:00",
  19:00: "19:00:00",
  19:30: "19:30:00",
  20:00: "20:00:00",
  20:30: "20:30:00",
  21:00: "21:00:00",
  21:30: "21:30:00",
  22:00: "22:00:00",
  22:30: "22:30:00",
  23:00: "23:00:00",
  23:30: "23:30:00",
  00:00: "00:00:00",
}

the result is ok but i dont sure about performance and is it the best way or not !

  • Related