0

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)

7
  • help me to find an error please Commented Oct 19, 2015 at 18:44
  • you have set the name of your variable to page with a value of products do: return view('products',compact('products')); then run your foreach Commented Oct 19, 2015 at 18:48
  • you also need to have a collection or variable called products like: $products = Product::orderBy('price','asc')->get(); Commented Oct 19, 2015 at 18:50
  • it did not solve my problem Commented Oct 20, 2015 at 4:25
  • have one more error (i am new in laravel) FatalErrorException in FrontController.php line 19: Class 'App\Http\Controllers\Product' not found Commented Oct 20, 2015 at 4:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.