Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

knubbe's avatar
Level 36

How to add number of days to date column in query

I have invoices table where I have date and pay_deadline. Pay deadline represent number of days from date of invoice that you have a time for pay. For example date=09/01/2024 and pay_deadline=7 that means that you have 7 days from 09/01/2024 to pay.

My question is:

How can I query for example all invoices that are still in time slot to pay? That means now() is between date and date + pay_deadline

Invoice::query()
    ->whereRaw(...)
0 likes
7 replies
LaryAI's avatar
Level 58

To solve this problem, you can use the whereRaw method to compare the current date with the date and date + pay_deadline in your query. Here's how you can do it:

use Carbon\Carbon;

$now = Carbon::now();

Invoice::query()
    ->whereRaw('? BETWEEN `date` AND DATE_ADD(`date`, INTERVAL `pay_deadline` DAY)', [$now])
    ->get();

Explanation:

  1. Carbon::now() gets the current date and time.
  2. whereRaw allows you to write a raw SQL query.
  3. ? BETWEEN date AND DATE_ADD(date, INTERVAL pay_deadline DAY) checks if the current date ($now) is between the date of the invoice and the date plus the pay_deadline days.

This query will return all invoices that are still within the time slot to pay.

knubbe's avatar
Level 36

@LaryAI Great! How to query same table but where date + pay_deadline is less then NOW()?

tykus's avatar

@knubbe

How to query same table but where date + pay_deadline is less then NOW()

Am I reading you right; date + pay_deadline < NOW() will be almost every record in the table; is this what you want?

tykus's avatar
tykus
Best Answer
Level 104

@knubbe in that case, the following query should work:

Invoice::query()
    ->whereRaw("DATE_ADD(`date`, INTERVAL `pay_deadline` DAY) < ?", [$now])
    ->get();
1 like

Please or to participate in this conversation.