laravel - 如何在来自请求 laravel 的 if-else 条件下重构参数?
问题描述
我的控制器中有这个功能,它检查参数请求并将其保存到我的表中以进行跟踪。但是,我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
因为每当在控制器的函数中添加新请求时,代码都会很长。
解决方案
你可以像这样尝试,但你需要验证或尝试捕获你需要处理的方法
这段代码可以是这样的
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
}
注意我不确定这是正确的答案,但这是解决这个问题的一个想法
推荐阅读
- filter - Mapbox GL JS 标记显示/隐藏
- macos - 将 CPLEX 升级到学术许可证 Mac
- python - 在 python 上设置 hebi 机器人
- java - 错误:无法找到或加载主类 sun.applet.AppletViewer。引起:java.lang.ClassNotFoundException:sun.applet.AppletViewer
- c# - Oauth 2.0 | 水疗 | id_token 是如何伪装成 access_token 来访问受限网络资源的?
- git - 根据扩展名将 git repo 文件移动到子文件夹
- docker - Docker 命令不做任何事情
- javascript - HTML5 画布:不绘图
- if-statement - 如何以最小份额的价值要求特定份额的海龟?
- css - Ionic 3:图像文件未加载到设备中