Laravel 5.7未定义变量

时间:2019-01-13 18:46:27

标签: laravel eloquent laravel-5.7

我正在尝试在单独的index.blade.php页面中显示产品,但是该页面没有打开,并且显示错误:

  

未定义变量:productsALL

@foreach($productsALL as $product)
    <img src="{{ asset('images/backend_images/products/small/'.$product->image) }}" alt="IMG-PRODUCT">
    {{ $product->product_name }}
@endforeach

路线

Route::get('/','IndexController@index');

IndexController

public function index()
{
    // Get all Products
    $productsAll = Product::inRandomOrder()->where('status', 1)->get();
    $productsAll = json_decode(json_encode($productsAll));

    // Get All Categories and Sub Categories
    $categories_menu = '';
    $categories = Category::with('categories')->where(['parent_id' => 0])->get();
    $categories = json_decode(json_encode($categories));
    /*echo "<pre>"; print_r($categories); die;*/
    foreach ($categories as $cat) {
        $categories_menu .= "
        <div class='panel-heading'>
            <h4 class='panel-title'>
                <a data-toggle='collapse' data-parent='#accordian' href='#" . $cat->id . "'>
                    <span class='badge pull-right'><i class='fa fa-plus'></i></span>
                    " . $cat->name . "
                </a>
            </h4>
        </div>
        <div id='" . $cat->id . "' class='panel-collapse collapse'>
            <div class='panel-body'>
                <ul>";
        $sub_categories = Category::where(['parent_id' => $cat->id])->get();
        foreach ($sub_categories as $sub_cat) {
            $categories_menu .= "<li><a href='#'>" . $sub_cat->name . " </a></li>";
        }
        $categories_menu .= '</ul>
            </div>
        </div>';
    }

    $banners = Banner::where('status', '1')->get();

    return view('index')->with(compact('productsAll', 'categories_menu', 'categories', 'banners'));
}

2 个答案:

答案 0 :(得分:4)

错误的部分在这里

return view('index')->with(compact('productsAll','categories_menu','categories','banners'));

将其更改为此

return view('index',compact('productsAll','categories_menu','categories','banners'));

希望它能起作用

答案 1 :(得分:0)

您可以使用with和compact方法将变量从控制器传递到视图。

1)第一种方法,
background-color: #333333; } #logo{ position: relative; } #home{ font-family: 'Raleway', sans-serif; text-align: center; } #about{ font-family: 'Raleway', sans-serif; } #location{ font-family: 'Raleway', sans-serif; }

2)第二种方法,
 $data=array('productsAll'=>$productsAll, 'categories_menu'=>$categories_menu, 'categories'=>$categories); return view('view')->with($data);
//Mostly i used this method for passing data in view

return view('index',compact('productsAll','categories_menu','categories','banners'));