Laravel 在控制器中添加超过 2 个参数

Laravel add more than 2 parameters in controller

在我的控制器中,我目前为视图提供了 2 个参数,如下所示:

return view('home')->with(['listings'=>$listings, 'featured_listings'=>$featured_listings]);

但是当我添加第三个参数时,它会给我以下消息:

Too few arguments to function App\Http\Controllers\HomeController::index(), 0 passed and exactly 1 expected

有什么方法可以从控制器向视图提供 2 个以上的参数吗?

如果你可以把参数像

return view('home', [
        'listings' => $listings, 
        'featured_listings' => $featured_listings,
        ..............................
]);

那你可以放2个以上

这个很简单,可以传递数据查看多个。有很多方法可以传递数据来查看。我建议你

return view('home',compact('listings','featured_listings','your_data',...));

There are few ways you can share data with a view. It is not limited to 1 or 2 parameters. You can share unlimited parameters.

选项 1

$categories = ProductCategory::all();
$brands = ProductBrand::all();
$product = Product::first();

return view('product.edit', compact(['categories', 'brands', 'product']));

选项 2

$categories = ProductCategory::all();
$brands = ProductBrand::all();
$product = Product::first();

return view('product.edit', ['categories' => $categories, 'brands' => $brands, 'product' => $product]);

选项 3

$categories = ProductCategory::all();
$brands = ProductBrand::all();
$product = Product::first();

return view('product.edit')->with('categories', $categories)->with('brands', $brands)->with('product', $product);