Laravel provides a powerful ORM for querying the database. At times, we might want to query the database in a very specific way.

In this guide, I will show you how to prepare simple Date Scopes for your use case and how to use them to query your Database.

//App/Utils/DateFilter.php startOfDay(); $end = now()->endOfDay(); break; case 'yesterday': $start = now()->subDay()->startOfDay(); $end = now()->subDay()->endOfDay(); break; case 'last 24 hours': $start = now()->subHours(24); $end = now()->endOfDay(); break; case 'last 7 days': $start = now()->subDays(6)->startOfDay(); $end = now()->endOfDay(); break; case 'this week': $start = now()->startOfWeek(); $end = now()->endOfDay(); break; case 'last 30 days': $start = now()->subDays(29)->startOfDay(); $end = now()->endOfDay(); break; case 'this month': $start = now()->startOfMonth(); $end = now()->endOfDay(); break; case 'last 90 days': $start = now()->subDays(89)->startOfDay(); $end = now()->endOfDay(); break; case 'last month': $start = now()->subMonth()->startOfMonth(); $end = now()->subMonth()->endOfMonth(); break; case 'quarter to date': $start = now()->startOfQuarter(); $end = now()->endOfDay(); break; case 'this year': $start = now()->startOfYear(); $end = now()->endOfDay(); break; case 'last year': $start = now()->subYear()->startOfYear(); $end = now()->subYear()->endOfYear(); break; case 'all time': $start = Carbon::createFromDate(1900, 1, 1)->startOfDay(); $end = Carbon::today()->endOfDay(); break; case 'custom': if ($customStart && $customEnd) { $start = Carbon::parse($customStart)->startOfDay(); $end = Carbon::parse($customEnd)->endOfDay(); } else { throw new Exception('Custom range requires start and end dates.'); } break; default: throw new Exception('Invalid period specified.'); } return ['start' => $start, 'end' => $end]; }

In this tutorial, we have covered how to prepare a simple date scope and how to query your database records using these date scopes.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners