首页 > 解决方案 > 如何在来自请求 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 conditionstoreTracking因为每当在控制器的函数中添加新请求时,代码都会很长。

标签: laravellaravel-requestlaravel-controller

解决方案


你可以像这样尝试,但你需要验证或尝试捕获你需要处理的方法

这段代码可以是这样的

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 
} 

注意我不确定这是正确的答案,但这是解决这个问题的一个想法


推荐阅读