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

Laravel中with()传参报错:参数2必须为可调用对象或null

解决Laravel视图传递Collection时的Type Error问题

嘿,我来帮你捋清楚这个问题!你碰到的错误提示 Type error: Argument 2 passed to with() must be callable or null, object given,核心意思是:你调用的 with() 方法期望第二个参数是闭包(可调用函数)或者null,但你传了一个Collection对象——这和你想把数据传递到视图的初衷完全不符。

错误原因

从你的代码来看,return view('welcome')->with('prices',$collection); 写法本身是正确的,但为什么会触发这个错误呢?大概率是这两种情况之一:

  • 你的Laravel应用存在视图缓存问题,导致PHP解析到了错误的with()方法重载;
  • 极少数情况下,代码上下文里view('welcome')返回的不是View实例(比如误写成redirect('welcome'),但你代码里是对的)。

解决方案

你可以尝试下面几种正确传递数据到视图的方式,同时清理缓存来解决问题:

方案1:直接在view()函数中传递数据数组

这是最简洁的写法,直接把数据作为第二个参数传给view():

Route::get('/', function (){ 
    $collection = collect(['product'=>'chair','price'=>100]); 
    return view('welcome', ['prices' => $collection]); 
});

方案2:保持链式with()写法(先清缓存)

如果你坚持想用链式调用,先清理视图缓存,再运行你的代码:

Route::get('/', function (){ 
    $collection = collect(['product'=>'chair','price'=>100]); 
    return view('welcome')->with('prices', $collection); 
});

执行缓存清理命令:

php artisan view:clear
# 或者清理所有缓存
php artisan optimize:clear

方案3:用with()传递数组参数

另一种链式调用的写法,把数据打包成数组传给with():

Route::get('/', function (){ 
    $collection = collect(['product'=>'chair','price'=>100]); 
    return view('welcome')->with(['prices' => $collection]); 
});

额外提示

在视图里使用$prices时,你可以通过{{ $prices['product'] }}或者{{ $prices->get('product') }}来访问Collection里的内容,两种方式都能正常工作。

内容的提问来源于stack exchange,提问作者sava milin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:44:59