KodaC's avatar
Level 1

Combine multiple conditions depending on boolean value in eloquent

I am currently trying to read out entries with dates (calendar) and would like to convert this as eloquent afterwards.

First I did the easy part

SQL:
SELECT id FROM visitors WHERE (screen_id = 1 OR screen_id IS NULL) AND enddate >= Carbon::now()

Eloquent:
Visitor::where(function ($query) {
    return $query->where('screen_id', $this->id)
        ->orWhereNull('screen_id');
})
    ->where('enddate', '>=', Carbon::now())
    ->get();

But now I can't get any further with the second part.

I would like to add the following conditions:

  • Start time (startdate) must be in the past ->where('start_at', '<=', Carbon::now()).
  • If the field show_whole_day is true, the entry should be displayed the whole day
  • If the field show_whole_day is false and startdate is today, the entry should be displayed only 300 minutes before start
  • If the field show_whole_day is false and startdate is not today (multi-day event), the entry on the current day should also be displayed 300 minutes before the start time (startdate = 2023-07-27 15:00 and enddate = 2023-07-30 10:00 - So I want the event between 28th and 30th to be displayed at 10:00).
0 likes
1 reply
Pixolantis's avatar
Level 2

For your second part you can use for example something like this

->where(function ($query) {
	$query->where(function ($query) {
		$query->where('show_whole_day', '=', 1)
			->where('startdate', '<=', Carbon::now()->endOfDay());
	})
		->orWhere(function ($query) {
			$query->where('show_whole_day', '=', 0)
				->whereDate('startdate', '<=', Carbon::now()->format('Y-m-d'))
				->whereTime('startdate', '<=', Carbon::now()->addMinutes(300)->format('H:i:s'));
		});
})
1 like

Please or to participate in this conversation.