删除 Laravel 中的重复代码- 优化

Remove duplication of code in Laravel- optimize

我想知道如何在不影响其在 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()

有些函数重复了所有常见的我怎样才能最小化这段代码

$user = User::where('id', $id)
            ->with('voucherUtilizations.voucher')
            ->with(['voucherUtilizations', function ($query) use($campaignId, $date_from, $date_to) {
                    $query->when(!empty($campaignId), function ($q1) use ($campaignId) {
                                return $q1->where('campaign_id', $campaignId);
                            });
                    $query->when(!empty($date_from), function ($q2) use ($date_from) {
                                return $q2->whereDate('created_at', '>=', $date_from);
                            });
                    $query->when(!empty($date_to), function ($q3) use ($date_to) {
                                return $q3->whereDate('created_at', '<=', $date_to);
                            });
                }])
            ->withCount('voucherUtilizations')
            ->whereNotNull('voucher_id')
            ->first();

使用when()或者也放置if条件,并且值存在于if条件则return值,所以不会添加2次相同的条件。

希望对您有所帮助。