如何修复此错误 "Undefined variable: products (0)"

how fix this error "Undefined variable: products (0)"

这是我的: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() 上使用 index 作为键,我希望您已经在视图中使用了 {{ $products }},所以您应该将 index 替换为 [=16] =] with() 就像下面一样

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

您可以像下面那样将数据作为数组传递给 view() 而不是使用 with(),您可以在视图中使用相应的键

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