Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel “如何修复此错误”;未定义变量:产品(0)";_Laravel_Laravel 5.7 - Fatal编程技术网

Laravel “如何修复此错误”;未定义变量:产品(0)";

Laravel “如何修复此错误”;未定义变量:产品(0)";,laravel,laravel-5.7,Laravel,Laravel 5.7,这是我的:IndexPageController <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Product; class IndexPageController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http

这是我的:IndexPageController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class IndexPageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // $products = Product::inRandomOrder()->take(10)->get();

        // return view('pages.index')->with('index', $products);
        $products = Product  ::inRandomOrder()->take(9)->get();
        return view ('pages.index')->with('index',$products);

    }
}

您正在使用
索引
作为
with()
的键,我希望您在查看时使用了
{{$products}
,因此您应该将
索引
替换为
products
on
with()
,如下所示

return view('pages.index')->with('products', $products);

您可以将数据作为数组传递给
视图()
而不是使用
with()
,如下所示,您可以在视图中使用相应的键

return view('pages.index', ['products' => $products]);

您可能需要向我们显示您的
页面。index
视图。您共享的所有代码都不会导致此错误。我怀疑您在视图中使用了
$products
,但您在
->with()
调用中命名了视图的变量
$index
。您可能使用了@ceejayoz所说的错误变量。尝试将
'index'
更改为
产品
@ceejayoz,你是对的,他确实在他的观点中使用了$products,你能写一个答案吗?你不应该只发布一个没有描述的图片链接的问题。检查问题写作规则。@AlexandruHort在你的匆忙中,你浪费了其他人的时间。上述代码之间有什么不同。我返回相同的答案。不客气:)但是有人否决了这个答案,但我仍然很高兴这个答案有帮助you@Sethu我没有投你反对票,但是我怀疑在这里否决每个答案的人这样做是因为他们都没有解释为什么需要更改。我否决了,因为没有解释,你在他链接图片之前写下了这个答案,所以我猜你读了我们的评论(答案在那里),只是把文本复制到了这个答案上。我很高兴OP解决了他的问题,但这不是我们做事的方式。@ceejayoz我能理解,谢谢你提供的信息