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

Ligonsker's avatar

whereMonth equivalent on collections

I have a query that I first need to use all of its data, then I need only the current month. There is a date column that has datetime value

If I have all the records in a collection, how can I now extract only the records from specific month?

Something similar to

$data = MyModel::whereMonth('created_at', Carbon::now()->month)->get();

But on a collection

0 likes
1 reply
LaryAI's avatar
Level 58

You can use the filter method on the collection to achieve this. Here's an example:

use Carbon\Carbon;

// Assuming you have a collection of MyModel objects called $collection
$currentMonth = Carbon::now()->month;

$filteredCollection = $collection->filter(function ($item) use ($currentMonth) {
    return $item->created_at->month === $currentMonth;
});

// $filteredCollection now contains only the MyModel objects with a created_at date in the current month

In this example, we're using the filter method to iterate over each item in the collection and return only the ones where the created_at date's month matches the current month. We're using the use keyword to pass the $currentMonth variable into the closure so we can access it inside the function.

Note that this solution assumes that the created_at attribute on your MyModel objects is a Carbon instance or something similar that has a month method. If it's just a plain string or timestamp, you'll need to modify the closure accordingly.

1 like

Please or to participate in this conversation.