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

jesse_orange_newable's avatar

Query returning unexpected results

In my application I have a Spotlight model.

I run this query:


Spotlight::newerThan(1)->published()->inRandomOrder()->take(2)->get();

Here are the query scopes.


/**
 * Scope an article by whether or not it's published
 * 
 */
public function scopePublished($query)
{
    return $query->where('status', 'published');
}

/**
 * Only retrieve Spotlights newer than the given increment
 *
 * @param [type] $query
 * @param [type] $interval
 * @return void
 */
public function scopeNewerThan($query, $interval)
{
    return $query->where('created_at', '<=', Carbon::now()->subMonths($interval)->toDateTimeString());
}

Dumping the actual query gives this:


"select * from `spotlights` where `created_at` <= 2019-10-01 16:14:27 and `status` = published order by RAND() limit 2"


However, I have no spotlights that are newer than one month, and yet it still returns something.

0 likes
6 replies
ftiersch's avatar
ftiersch
Best Answer
Level 28

"newerThan" would be a >=, not a <= :) You accidentally programmed "olderThan"

1 like
jesse_orange_newable's avatar

*Facepalm - is there an easy way to remember older and newer with dates, I always get these confused.

Sinnbeck's avatar

Older points backwards aka the past <

Newer points forwards aka the future >

1 like
ftiersch's avatar

Nah, I think he means imagining it as a timeline :) Left is 0 so if you point the arrow to the left < you check for "older"

Please or to participate in this conversation.