0

I want to filter data given from eloquent laravel. I have 4 date picker in my view, and I want when each of one has filled and has date the query change. This is my code in controller

if ($start_publish && $end_publish && $start_close && $end_close) {
                $data = Tender::where('published_at','>=',$start_publish)->where('published_at','<=',$end_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);

}elseif (!$start_publish && $end_publish && $start_close && $end_close) {
                $data = Tender::where('published_at','<=',$end_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);

} elseif ($start_publish && !$end_publish && $start_close && $end_close) {
                $data = Tender::where('published_at','>=',$start_publish)->where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);

} elseif (!$start_publish && !$end_publish && $start_close && $end_close) {
                $data = Tender::where('closed_at','>=',$start_close)->where('closed_at','<=',$end_close);

} elseif ($start_publish && $end_publish && !$start_close && $end_close) {
                $data = Tender::where('published_at','>=',$start_publish)->where('published_at','<=',$end_publish)->where('closed_at','<=',$end_close);
            }
            elseif ($start_publish && $end_publish && $start_close && !$end_close) {
                ...
                ...
                ...
        } else {
            $data = Tender::get();
        }

Because I have 4 input, the number of states for the condition is equal to 16 and the code is messy.

Does anyone have an idea to refactor the code?

1 Answer 1

1

The idea: if your variable is set, you check it. Otherwise not

You could try with this ( this is an idea, not the actual code )

$builder = Tender::query();
if($start_publish) $builder->where('published_at','>=',$start_publish);
if($start_close) $builder->where('closed_at','>=',$start_close);
...
return $builder->get()

.... and so on

Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I wanted. Thanks

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.