0

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.

4

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was asking if there was a ready eloquent way to achieve this but since it seems there is not this is a good start. Thanks.
Yeah, not that I am aware of - I think you have to craft the query yourself with your input. If you DO find a better way - let me know! I run up against similar queries often!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.