lundi 6 avril 2020

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire