How can I select all Eloquent models from a MySQL database inserted today, within the last week or the last month?

StackOverflow https://stackoverflow.com//questions/24011954

Question

I have an Eloquent Model (Test) associated with a MySQL table called tests, with the following structure:

tests
id          int
created_at  date
updated_at  date
correct     boolean

I am trying to select only those tests created today, within the last 7 days and within the last month, something like this (pseudocode):

$todays_tests = Test::where('created_at','=', 'today');
$this_weeks_tests = Test::where('created_at','=', 'last 7 days');
$this_months_tests = Test::where('created_at','=', 'last month');

I'm sure Laravel provides an easy way to do this but I'm not sure how best to go about it. Presumably I need to use a raw MySQL query?

Many thanks,

Was it helpful?

Solution

I am sure you can do some nice things with the Carbon plugin. The Carbon documentation: https://github.com/briannesbitt/Carbon

For example for created today, if you add this in your Test model:

public function scopeCreatedToday($query)
{
    return $query->whereBetween('created_at', array(Carbon::today(), Carbon::today()->addDay()));
}

You will be able to do: $tests = Test::createdToday()->get();.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top