Snippets

Laravel where() and orWhere() condition together for one column

If you are in a situation where you need to use Laravel where() and orWhere() condition together for one column, this tip might be helpful for you. Let's dig into a real life scenario.

Imagine that, I am checking send_at column. It can be both, either null or have timestamp value.

#What need to achieve?

  • Get records if send_at is null.
  • Get records also if send_at has value and then add a condition on that value. Probably time in certain time ago.

Appointment::whereNull('send_at')
	->orWhere(function($query) {
	    $query->whereNotNull('send_at')
	    	->where('send_at', '<', now()->subMinutes(50)]);
	})->get()

This code will check-

  • Whether send_at value is null or not.
  • If it has value, then check whether the send_at value is less than 50 minutes ago from now or not.

Hope it will help you.

Thanks.