You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何在DELETE端点获取表单输入参数

问题

路由配置如下:

Route::prefix('traffic-table')->group(function() {
      Route::delete('/{id_olt}', 'Api\TrafficTableController@remove');
   });

控制器方法尝试获取请求参数:

public function remove($id_olt, Request $request)
{
    return response()->json($request->all());
}

使用以下curl请求调用时,返回空数组:

curl --location --request DELETE 'localhost/api/traffic-table/41' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer 2|jY4c7vBFTTG9Jb0cW1NAgm6Kr0gTFLeJO9t9Nu8I' \
--form 'id="1010"'

请问除了通过URL传递外,如何获取该id参数?

解决方案

1. 改用JSON格式传递参数

DELETE请求默认不会解析multipart/form-data类型的参数(也就是curl的--form选项),换成JSON格式传递是更符合REST规范的方式:

修改curl请求:

curl --location --request DELETE 'localhost/api/traffic-table/41' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer 2|jY4c7vBFTTG9Jb0cW1NAgm6Kr0gTFLeJO9t9Nu8I' \
--header 'Content-Type: application/json' \
--data-raw '{
    "id": "1010"
}'

控制器中直接通过$request->input('id')即可获取参数。

2. 通过Query String传递参数

将id作为URL的查询参数携带:

curl --location --request DELETE 'localhost/api/traffic-table/41?id=1010' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer 2|jY4c7vBFTTG9Jb0cW1NAgm6Kr0gTFLeJO9t9Nu8I'

控制器中可以用$request->query('id')或者$request->input('id')获取该参数。

3. 手动解析multipart/form-data(不推荐)

如果必须使用表单格式传递,需要手动解析请求体,但这种方式不符合REST设计规范,不建议使用:

public function remove($id_olt, Request $request)
{
    // 方法1:读取原始请求体并解析
    $rawData = file_get_contents('php://input');
    parse_str($rawData, $data);
    $id = $data['id'] ?? null;

    // 方法2:直接读取POST全局变量
    // $id = $_POST['id'] ?? null;

    return response()->json(['id' => $id]);
}

内容的提问来源于stack exchange,提问作者Luis Urán

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:05:33