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

haroon373's avatar

Date comparison on Eloquent Model Collection

Hi,

I have a scenario that I don't want to query the database 4 times so my first line of code is:

$proposals = ProposalModel::get();

Now I want to fetch all pending proposals, (that is working)

$pending = $proposals->where('status', 'pending');

But, for the approved, submitted and declined proposals, I want to fetch the records according to dates. For example, get records of approved proposal of last 30 days

$approved = $proposals->where('status', 'approved')->where('created_at', '>=', \Carbon\Carbon::now()->subMonth());

created_at is datetime field in database.

Is it possible, not permitted, or else? Please let me know how can I do that. Again, I don't want to query database again and again for all 4 different statuses of my proposal.

Thanks and Regards,

0 likes
2 replies
manelgavalda's avatar
Level 50

You can use filter to compare the dates. created_atis a carbon instance, so you can do something like this (btw you can use the laravel helper now):

    $approved = $proposals->where('status', 'approved')->filter(function($proposal) {
        return $proposal->created_at->gte(now()->subMonth());
    });
1 like
haroon373's avatar

@MANELGAVALDA - Wow, that's really a simple one. Though, I made a little change in the code

$approved = $proposalsAll->where('status', 'approved')->filter(function($proposal) {
            return Carbon::parse($proposal->created_at)->gte(\Carbon\Carbon::now()->subMonth());
        });

But, thank you so much for introducing me with filter.

This solved my problem.

Many kudos.

1 like

Please or to participate in this conversation.