0

I need to get the difference between 2 dates but not only between 2 specific dates, I am talking about a table that has the "pdt_expires" column, and I want to show how much days until this date, but in EVERY rows. Ex:

  • Rice - 2 lb - expires in 54 days
  • Beans - 3 lb - expires in 31 days

I saw THOUSAND of solutions for only 2 specific dates but none for this case. I wonder I would need:

  • a function in Product Model that access the "pdt_expire" and use Carbon to get the final value

OR - a function inside the View that get the $product->pdt_expire and get the final value

So any help would be great, thank you.

Jeú Casulo
  • 139
  • 2
  • 11

1 Answers1

4

How about achieve it using just simple DATEDIFF query:

ProductModel::select([
    'products.*',
    \DB::raw('DATEDIFF(pdt_expires, NOW()) as expires_in')
])->get();

So in every product you have, it will have an additional column called expires_in that stores different of days between NOW to pdt_expires.

DATEDIFF: How to get the number of days of difference between two dates on mysql?

Community
  • 1
  • 1
Lionel Chan
  • 7,894
  • 5
  • 40
  • 69
  • Thought I would never say that but it really works, but tell me pls, you kind of created this "new virtual column" called expires_in in the table so the query can access it now? Really thank you fellas, lost all my day in that scenario! Thankyou! – Jeú Casulo Nov 03 '16 at 04:36
  • Not really virtual column, but just standard feature in sql. Since you are doing the diff of days, why not do it in the single query? Of course you can do it like using Laravel's mutators, but that would be a little bit overkill for this simple query – Lionel Chan Nov 03 '16 at 04:46
  • Got it! Thank you again fella, this really helps a lot in my project – Jeú Casulo Nov 12 '16 at 22:14
  • Any chance using a where clause in this query? Trying the casual way but the expires_in column does not exist – Jeú Casulo Nov 17 '16 at 19:08