Level 54
Try something like this:
$posts = Post::whereRaw(
'DATE_FORMAT(created_at, ?) <= ?',
[
'%Y%m',
Carbon::now()->format('Ym')
]
)->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, i have a view in my application that returns all posts submitted, however i want to filter this posts by month, but i still haven't found a way to show values filtered by date, right now this is what i have:
public function Api(){
// Variable from the current month
$dt = Carbon::now();
$today = strval($dt->month);
//Since all the posts i've been creating are older than the current month i stablished this conditional
$posts = Post::all()->where('created_at->format("m")', '<=', $today);
//This doesn't work either.
->where('created_at', '<=', $today);
return Response::json([
'exitos' => $exitos->toArray(),
], 200);
}
But this returns an empty array.
Or, if you wanted all posts between two dates, this ought to work:
// Fetch all posts between the first of this year and now:
$start = Carbon::parse('2016-01-01')->toDateString();
$end = Carbon::now()->toDateString();
$posts = Post::whereBetween('created_at', [$start, $end])->get();
Please or to participate in this conversation.