我的结帐页面上有一个AJAX请求,用户可以输入优惠券代码。这样就进入了我的控制器:
public function attachCoupon(AttachCouponRequest $request)
{
$response = ShopHelper::checkCoupon($request->coupon);
return Response::json($response);
}
我的检查优惠券'函数从辅助类加载,看起来像这样:
public static function checkCoupon($code)
{
$coupon = Coupon::where('code',$code)->get();
if ($coupon->isEmpty()) {
$response = ['valid' => false, 'message' => 'Coupon code not recognised'];
} elseif ( isset($coupon->end_date) && $coupon->end_date < Carbon::now()) {
$response = ['valid' => false, 'message' => 'Sorry, that coupon has expired.'];
} elseif ( isset($coupon->start_date) && $coupon->start_date > Carbon::now()) {
$response = ['valid' => false, 'message' => 'Sorry, that coupon is not yet valid.'];
} elseif ( isset($coupon->status) && $coupon->status === 'inactive') {
$response = ['valid' => false, 'message' => 'Sorry, that coupon is inactive.'];
} else {
$response = ['valid' => true, 'message' => 'Coupon applied successfully!.'];
}
return($response);
}
这看起来非常不像laravel,有没有更简洁的方法来做到这一点?我可以将它放入我的FormRequest课程&#39; AttachCouponRequest&#39;?我应该使用服务提供商吗?
请帮我把它变得更优雅。
谢谢。
答案 0 :(得分:1)
目前,您正在使用Eloquent调用get(),但方法名称表示您只是检查它是否是有效的优惠券。
那么,为什么不更改查询,以便您在优惠券本身上应用过滤器并返回通用成功/失败响应?
例如:
$coupon = Coupon::where('code',$code)
->where('end_date', '>=', Carbon::now())
->where('start_date', '<=', Carbon::now())
->where('status', '!=', 'inactive')
->count();
if (! $count) {
return ['valid' => false, 'message' => 'Sorry, that coupon is not valid.'];
}
return ['valid' => true, 'message' => 'Coupon applied successfully!'];
然后,您可以利用查询范围,以便您可以执行此类操作,以提高可读性:
$coupon = Coupon::where('code', $code)->onlyActive()->get();