muhammad arslan
muhammad arslan

Reputation: 11

laravel undefined variable error in foreach

this is my controller function

public function products() {

    return view('products', array('page' => 'products'));
}

this is view

@foreach ($products as $product)

this is route

Route::get('products','FrontController@products');

this is error

Undefined variable: products (View: C:\xampp\htdocs\OSM\resources\views\products.blade.php)

Upvotes: 0

Views: 11409

Answers (1)

Akshendra Pratap
Akshendra Pratap

Reputation: 2040

The way you are passing the data to view, is making a variable named $page with the value of "products".

Inside your controller, you will need to grab the products data you want passed to the foreach loop and save it to a variable. Assuming that you already have an Eloquent model called 'Product', you could call $products = Product::all(); and this would return a Collection of every Product. Then you can pass that to your views using

  • view('products')->withProducts($products)
  • view('products')->with('products', $products);
  • view('products', ['products' => $products]);

There are other methods as well, for example using compact if you have a variable named $products and $page like

view('products', compact('products', 'page'));

compactbasically creates an array using with variable names as keys and variable values as the corresponding values.

Upvotes: 1

Related Questions