我的控制器中有一个函数,它检查参数请求并将其保存到我的表中进行跟踪。但是,我的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函数中添加新请求时,代码都会很长。
发布于 2021-03-04 03:48:52
您可以这样做,但您需要验证或尝试捕获,您需要处理
这个代码可以是这样的
foreach ($request->except('_token') as $key => $value) {
$traffic = new TrafficTracking();
$traffic->traffic_type = $key;
$traffic->traffic_value = $value;
$traffic->save();
break; // if you want single time execution
} 注意到我不确定答案是否正确,但这是一个解决
问题的方法。
发布于 2021-03-04 04:12:44
使用三元操作符的
(Condition) ? (Statement1) : (Statement2);条件:它是要计算的表达式,它返回一个布尔值。
语句1:如果条件导致真状态,则执行该语句。
语句2:如果条件导致false状态,则执行该语句。
使用开关外壳的
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
} https://stackoverflow.com/questions/66468167
复制相似问题