Home / Snippets / Laravel ​whereDay()​, ​whereMonth()​, ​whereYear()​, whereDate()​ and ​whereTime()
Laravel ​whereDay()​, ​whereMonth()​, ​whereYear()​, whereDate()​ and ​whereTime() cover

Laravel ​whereDay()​, ​whereMonth()​, ​whereYear()​, whereDate()​ and ​whereTime()

430

3 years ago

0 comments

In Laravel, you can make use of the date methods to get specific data based on the specified date condition. Below are the examples of how to use them.

whereDay
You can use whereDay to query your eloquent by the day of the month.
Post::whereDay('created_at', '02')
  ->get(['title', 'created_at'])
  ->toArray(); 

The result will be as follows
[
  [
    "title" => "How to Increase PHP upload_max_filesize via Laravel Forge",
    "created_at" => "2021-02-01T21:36:01.000000Z",
  ],
  [
    "title" => "Laravel Eloquent, select only rows where the relation exists",
    "created_at" => "2021-02-01T19:38:56.000000Z",
  ],
];

whereMonth
You can use whereMonth to query your eloquent model by month.
Post::whereMonth('created_at', '07')
  ->get(['title', 'created_at'])
  ->toArray();

The result will be as follows.
[
  [
    "title" =>
      "How to Implement Light and Dark Mode with AlpineJs and TailwindCSS",
    "created_at" => "2021-07-04T00:00:53.000000Z",
  ],
];

whereYear
You can use whereYear to query your eloquent model by year.
Post::whereYear('created_at', '2020')
  ->get(['title', 'created_at'])
  ->toArray();

The result will be as follows.
[
  [
    "title" => "5 productivity tool for MacOS users",
    "created_at" => "2020-12-20T01:35:18.000000Z",
  ],
  [
    "title" => "How to easily generate Android and IOS app icons",
    "created_at" => "2020-12-20T01:37:24.000000Z",
  ],
  // etc
];

whereDate
You can use whereDate to query by date but do note that the date format is important.
Post::whereDate('created_at', '2021-06-28')
  ->get(['title', 'created_at'])
  ->toArray();

The result will be as follows.
[
  [
    "title" => "How to Deploy Laravel 8 to Production with Laravel Forge",
    "created_at" => "2021-06-28T14:54:50.000000Z",
  ],
];

whereTime
Finally you can make use of the whereTime to query by the time. Make sure to use a specific time to get the result.
Post::whereTime('created_at', '09:35:18')
  ->get(['title', 'created_at'])
  ->toArray();

The result will be as follows.
[
  [
    "title" => "5 productivity tool for MacOS users",
    "created_at" => "2020-12-20T01:35:18.000000Z",
  ],
];
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this