lundi 7 juin 2021

Remove duplication of code in Laravel- optimize

I want to how to optimize my code below without affecting its output in laravel?

 $user = User::with('voucherUtilizations.voucher')
                ->with('voucherUtilizations', function ($query) use($campaignId ,$date_from,$date_to) {
                    if ($campaignId && $date_from &&$date_to) {
                        return $query->where('campaign_id', $campaignId)
                                     ->whereDate('created_at', '>=', $date_from)
                                     ->whereDate('created_at', '<=', $date_to)
                                     ->whereNotNull('voucher_id');
                    }
                    if ($campaignId) {
                        return $query->where('campaign_id', $campaignId)
                                     ->whereNotNull('voucher_id',);
                    }
                    if ($date_from &&$date_to) {
                        return $query->whereDate('created_at', '>=', $date_from)
                                     ->whereDate('created_at', '<=', $date_to)
                                     ->whereNotNull('voucher_id');
                    }
                })
                ->withCount(['voucherUtilizations as no_of_prizes_won' => function ($query) use($campaignId ,$date_from,$date_to){
                    //the same code above function
                }])
                ->where('id', $id->id)
                ->first()

some functions are repeated all common how can I minimize this code



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3pwjeii
via IFTTT

Aucun commentaire:

Enregistrer un commentaire