Reputation: 609
I'm working to show products in a separate index.blade.php page but the page is not opening and it gives the error:
Undefined variable: productsALL
@foreach($productsALL as $product)
<img src="{{ asset('images/backend_images/products/small/'.$product->image) }}" alt="IMG-PRODUCT">
{{ $product->product_name }}
@endforeach
Route
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'));
}
Upvotes: 0
Views: 1671
Reputation: 1073
You can pass the variable from controller to view by using both the with and compact method.
1)First method,
$data=array('productsAll'=>$productsAll, 'categories_menu'=>$categories_menu, 'categories'=>$categories);
return view('view')->with($data);
2) Second method,
//Mostly i used this method for passing data in view
return view('index',compact('productsAll','categories_menu','categories','banners'));
OR,
$data=array('productsAll','categories_menu','categories','banners');
return view('view')->compact($data);
Upvotes: 0
Reputation: 274
the wrong part is here
return view('index')->with(compact('productsAll','categories_menu','categories','banners'));
change it to this
return view('index',compact('productsAll','categories_menu','categories','banners'));
hope it works
Upvotes: 4