Jihun
Jihun

Reputation: 93

How to do conditional query in Laravel

The situation is following. The table has 2 date fields and last date is nullable.

enter image description here

In this table I want to get the 1st and 2nd records when I pass 2020-02-10 as parameter. That is between start_end and end_date or bigger than start_date if end_date is null.

How to do Laravel eloquent for this. Thank you in advance.

Upvotes: 2

Views: 218

Answers (1)

Clément Baconnier
Clément Baconnier

Reputation: 6108

It's kind of ugly, but I think something like that should work

Model::where(function($query) use ($date){
    $query->where('start_date', '<=', $date)
        ->where('end_date', '>=',  $date);
})->orWhere(function($query) use ($date) {
    $query->where('start_date', '<=', $date)
        ->whereNull('end_date');
})->get()

Edit Since you need other condition with it, you need to wrap this condition

Model::query()
->where(function($query) use ($date) {
    $query->where(function($query) use ($date){
        $query->where('start_date', '<=', $date)
            ->where('end_date', '>=',  $date);
    })->orWhere(function($query) use ($date) {
        $query->where('start_date', '<=', $date)
            ->whereNull('end_date');
    })
})
->where('another_column', true)
->get()
```

Upvotes: 1

Related Questions