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

Laravel:重定向时如何附加Request实例?

问题解决:重定向时传递Request参数到指定路由

你当前代码里直接把Request实例传入route()方法是无效的,Laravel的路由重定向不支持直接传递Request对象,需要把Request里的参数提取出来作为查询字符串附加到重定向URL中。

核心问题分析

redirect()->route()的第二个参数仅接受路由占位符对应的参数,或者额外的查询参数数组。直接传入Request实例会被强制转换为字符串,无法传递实际参数。

修改后的控制器代码

public function return(Request $request, $order_id)
{
    $order = Order::with([
        'products' => fn ($q) => $q->with('thumbnail')
    ])->findOrFail($order_id);

    if ($request->method() == 'GET') {
        return view('front.orders.return_products', compact('order'));
    } elseif ($request->method() == 'DELETE') {
        $newRequest = new Request([
            'products_ids' => $order->products->pluck('id')->toArray(),
            'quantities' => $order->products->pluck('pivot.quantity')->toArray(),
        ]);

        // 方式1:使用query()方法附加查询参数
        return redirect()->route('front.orders.return-calc', $order_id)
            ->query($newRequest->all());

        // 方式2:将参数合并到路由参数数组中,Laravel自动转为查询字符串
        // return redirect()->route('front.orders.return-calc', [
        //     'order_id' => $order_id,
        //     ...$newRequest->all()
        // ]);
    }
}

目标路由方法接收参数

在returnCalc方法中,你可以直接通过Request实例获取传递的参数:

public function returnCalc(Request $request, $order_id)
{
    $productIds = $request->input('products_ids');
    $quantities = $request->input('quantities');
    // 后续逻辑处理
}

补充说明

  • 如果需要临时存储参数而非暴露在URL中,可以使用->with($newRequest->all()),但参数会存在Session中,目标方法需要通过session()或$request->session()->get()获取,且仅在下次请求有效。
  • 注意变量名冲突:避免在DELETE分支中覆盖原$request变量,建议重命名为$newRequest,防止后续代码出现意外问题。

内容的提问来源于stack exchange,提问作者Ahmed Alaa El-Din Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:45:57