Ad

Refactor Laravel Eloquent Query

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?

Ad

Answer

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

Ad
source: stackoverflow.com
Ad