【问题标题】:Undefined variable error in Layouts (Laravel)布局中的未定义变量错误(Laravel)
【发布时间】:2020-02-13 18:38:52
【问题描述】:

我试图从 laravel Blade 中的布局中生成一个部分,但问题是当我 yield 时没有定义 var

这是我的代码:

web.php:

Route::get('/pr','ProductController@carousel');

产品控制器:

    public function carousel()
    {
        $Proudcts= Product::select('name','amount','dis_amount','stock','company_id','category_id','pic_url')->get();
        return view('product-carousel')->with('products', $Proudcts);
    }

产品-carousel.blade.php:

@include('include.head')
<body>
@section('product-carousel')
<div class="owl-carousel owl-theme">
@foreach($products as $product)
<div class="product-carousel item ">
    <a>
        <img  src="{{$product->pic_url}}" style='height: 400px; width: 100%; object-fit: contain'/>
        <h4 lang="en_US" class="product-name-show">{{$product->name}}</h4>
        <h3 class="amount-for-product">
            Buy
        </h3>
    </a>
</div>
@endforeach
</div>
<script src="/js/owl.js" type="text/javascript" language="JavaScript"></script>
@endsection
</body>
</html>

index.blade.php:

@include('include.head')
@extends('product-carousel')
@yield('product-carousel')

如您所见,我在“index.blade.php”中扩展了“product-carousel.blade.php”并生成了“@section('product-carousel')”,问题是 $products 在“index.blade.php”中不存在

但正在“product-carousel.blade.php”中工作

这是错误: 未定义变量:产品

【问题讨论】:

  • 您还应该在调用索引视图的控制器中通过 with 传递 products 变量。
  • @MauroBaptista 我知道,但工作量太大了

标签: php laravel laravel-blade


【解决方案1】:

如果您希望变量在视图存在时可用,请在 AppServiceProviderboot 函数中使用视图编辑器

public function boot()
{
    view()->composer(['index', 'product-carousel'], function ($view) {
        $products = \App\Product::select('name', 'amount', 'dis_amount', 'stock', 'company_id', 'category_id', 'pic_url')->get();
        return $view->with('products', $products);
    });
}

希望对你有帮助

【讨论】:

  • 更新了我的答案,尝试查看作曲家
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
相关资源
最近更新 更多