【问题标题】:Laravel $product_cat is undefined?Laravel $product_cat 未定义?
【发布时间】:2021-04-21 03:09:22
【问题描述】:

我想在模板布局中在我的网站上显示我的类别。我收到错误:“未定义变量:$product_cat”。

[家庭控制器]

public function index()
{
    $bestseller = DB::select('select * from product where popular = ? AND p_status = ?', ['Yes', 'Active']);
    $hotpick = DB::select('select * from product where p_hot = ? AND p_status = ?', ['Yes', 'Active']);
    $product_cat = DB::table('pro_category')->where('pc_status', 'Active');
    return view('welcome', ['bestseller'=>$bestseller], ['hotpick'=>$hotpick], ['product_cat'=>$product_cat]);
}

[welcome.blade.php]

@foreach($product_cat as $product_cat)
                <div class="dropdown-menu full" aria-labelledby="dropdownMenuButton">
                    <center>
                <a class="dropdown-item full" href="#">{{$product_cat->pc_name}}</a>
            </center>
        @endforeach

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    检查您从 pro_category 表中获取数据的行。确保您正在从中检索数据。

    只要 dd($product_cat) 看看

    $product_cat = DB::table('pro_category')->where('pc_status', 'Active');
    dd($product_cat);
    

    在您看来,您正在使用$product_cat as product_cat 我建议您使用不同的值,例如

    $foreach ($product_cat as $category){
      //Your code goes here
    }
    

    在你的控制器返回视图中包含这样的数据

     return view('welcome', [
       'bestseller'=>$bestseller, 
       'hotpick'=>$hotpick, 
       'product_cat'=>$product_cat
    ]);
    

    【讨论】:

    • 我认为返回视图不能超过 2 值。你有没有找到任何可能的方法来实现它?
    • 这样做返回视图('welcome', ['bestseller'=>$bestseller, 'hotpick'=>$hotpick, 'product_cat'=>$product_cat]);
    【解决方案2】:
    1. 您应该尽可能使用 ORM 查询(如果您发布数据库,我可以为您构建 ORM 查询)

    2. 您应该像这样在同一个数组中返回所有内容:

     return view('welcome', [
    
    'bestseller'=>$bestseller,
    'hotpick'=>$hotpick,
    'product_cat'=>$product_cat
    ]);
    
    1. 您还应该为别名指定不同的名称,而不是使用 foreach 运行的变量的相同名称
    @foreach($product_cats as $product_cat)
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-23
      • 2019-08-10
      • 2020-03-03
      • 2018-08-02
      • 2019-01-01
      • 2018-04-06
      • 2012-08-24
      • 2019-04-29
      相关资源
      最近更新 更多