【发布时间】:2021-06-02 16:41:00
【问题描述】:
我的控制器中有这个功能,它检查参数请求并将其保存到我的表中以进行跟踪。但是我的if condition 太长了,因为每当添加新请求时,我都必须在每个请求中写入单独的if condition。
这是我的代码:
public function storeTracking(Request $request)
{
$traffic = new TrafficTracking();
if ($request->has('gclid')) { // check if request = gclid
$traffic->traffic_type = 'gclid';
$traffic->traffic_value = $request->gclid;
}
if ($request->has('token')) { // check if request = token
$traffic->traffic_type = 'token';
$traffic->traffic_value = $request->token;
}
if ($request->has('fbclid')) { // check if request = fbclid
$traffic->traffic_type = 'fbclid';
$traffic->traffic_value = $request->fbclid;
}
if ($request->has('cjevent')) { // check if request = cjevent
$traffic->traffic_type = 'cjevent';
$traffic->traffic_value = $request->cjevent;
}
$traffic->save();
return response()->json([
'message' => 'success'
], 200);
}
对于if condition,有没有更短的方法?因为每当在控制器的storeTracking 函数中添加新请求时,代码都会很长。
【问题讨论】:
-
如果有多个条件可以使用switch case或者使用三元运算符
-
@RushikeshGanesh 你能给我们举个例子吗?为了将来的目的,其他人可能会遇到同样的问题,他们可以复制它。
标签: laravel laravel-request laravel-controller