Search code examples
phplaraveleloquent

Laravel eloquent fetching records based on values in the table


So I have a Tasks table that has a time field and a "minutes" field. I want to fetch only records based on the time and minutes field, something like so:

$tasks = Task::whereTime('time', '<=', Carbon::now()->addMinutes(DB::raw('minutes'))->format('H:i'))->get();

Let's say a task is due at 03:00 so the time field will be 03:00. Exactly 30 minutes before the task is due, I want to get a notification, so when the current time is 02:30.

So in this example, the "minutes" field is 30. Now, when fetching the records, I am using the above query. It does not work, but the below does work:

$tasks = Task::whereTime('time', '<=', Carbon::now()->addMinutes(30)->format('H:i'))->get();

Perhaps there is an easier/better way to approach this, but I want to get only the records from the database that will be used, and I do not want to perform multiple checks after fetching all records. So my question is, can this be done using eloquent or should I just fetch all records and perform some time checks after looping over all tasks?


Solution

  • Try to use whereRaw so that you can customize the query.

    $tasks = Task::whereRaw('TIME(NOW()) >= TIME(SUBTIME(tasks.time, CONCAT("0:",minutes, ":0")))')->get();
    
    

    ADDTIME is a function that adds a time to a time/DateTime format

    for example, ADDTIME("00:00:00", "00:30:00"), adds 30 minutes to the initial time. I wrapped it in a time() function so I could compare it easily. I also used the Concat function to create a time format like string

    Read more about ADDTIME