prgrm
prgrm

Reputation: 3833

Getting specific date ranges from database in Laravel

I need to get results from a DB divided by dates such as today, yesterday, this week, last week, etc.

I can easily do this with whereRaw and some SQL:

whereRaw('Date(created_at) = CURDATE()')->get();

I wonder if there is an easier, proper way to do this with Eloquent.

Upvotes: 0

Views: 844

Answers (1)

Hanny
Hanny

Reputation: 2159

You could create a scope for a particular class like this:

public function scopeYourQuery($query, $user) {
    return $query->where('user_id', $user->id)->orderBy('created_at', 'desc')->first();
}

This just gets the first item of a descending ordered list ordered by created_at date per user.

If you wanted something that was between date ranges? You just pass in your date and extend it a bit with some PHP, maybe something like this would work:

public function scopeSomeDateQuery($query, $fetch_date, $user)
{
    //clone the users chosen month - so we can make the range until the following month
    $also_fetch_date = clone $fetch_date;
    $next_month = $also_fetch_date->addMonth();
    $next_month = $next_month->format('Y-m-d');
    $fetch_date = $fetch_date->format('Y-m-d');
    //return the query for the monthname
    return $query->orderBy('created_date')->where('created_date', '>=', $fetch_date)->where('created_date', '<', $next_month)->where('user_id', $user->id);
}

This would look in a monthly range (per user) to get an ordered list of items with a created_date in that range.

Upvotes: 1

Related Questions