Skip to content
Advertisement

Laravel Eloquent – Specific Date Filtering

I have a Laravel app that sends reminders on specific days prior to a tenancy_start_date. Essentially every 3 days, then 2 days, then daily ([30, 27, 24, 21, 19, 17, 15, 13, 11, 9, 8, 7, 6, 5]) Is there a neater way to code this:

User::where('active', 1)
            ->where('setup_status', '<', 9)
            ->where(function ($q) {
                $q->where('tenancy_start_date', '=', now()->addDays(31)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(28)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(25)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(22)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(20)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(18)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(16)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(14)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(12)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(10)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(9)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(8)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(7)->toDateString())
                ->orWhere('tenancy_start_date', '=', now()->addDays(5)->toDateString());
            })->get();

Advertisement

Answer

What is your database? You can use specific date difference functionality. For example in MySQL, you can try this:

where(DB::raw('DATEDIFF(tenancy_start_date, now()) in 
              (30, 27, 24, 21, 19, 17, 15, 13, 11, 9, 8, 7, 6, 5)')

In PostgreSQL you also use DATEDIFF but you have to specify day as parameter. In other database engines you can research for similar solution

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement