Chris
Chris

Reputation: 14198

eloquent only apply where if column is not null

I have the following where queries chained:

->where('start_timestamp', '<=', $activity->timestamp)
->where('end_timestamp', '>=', $activity->timestamp)
->where('minimum_activity_distance', '<=', $activity->distance)
->where('maximum_activity_distance', '>=', $activity->distance)
->where('minimum_activity_duration', '<=', $activity->duration)
->where('maximum_activity_duration', '>=', $activity->duration)
->where('minimum_activity_timestamp_time', '<=', $activity->timestamp->format('H:i:s'))
->where('maximum_activity_timestamp_time', '>=', $activity->timestamp->format('H:i:s'));

However, the columns may also be NULL. And if so, I do not want the condition to be applied.

so if minimum_activity_distance is NULL I want to skip/ignore

->where('minimum_activity_distance', '<=', $activity->distance)

Upvotes: 0

Views: 556

Answers (1)

Cl&#233;ment Baconnier
Cl&#233;ment Baconnier

Reputation: 6058

You can use where with a closure for this

   ->where(function ($q) use ($activity) {
       $q->where('minimum_activity_distance', '<=', $activity->distance)
          ->orWhereNull('minimum_activity_distance');
    })

Upvotes: 1

Related Questions