2

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.

1 Answer 1

1

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()
```
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for quick answer. If I have another fields like is_deleted and I should check the field how to implement multiple condition?
You need to wrap the where and the orWhere in an another where(function($query){....} (three level deep) See the anonymous function as parenthesis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.