I keep getting
Undefined variable: products
products.blade
@foreach ($products as $prod)
<td>{{ $prod->name }} </td>
<td>{{ $prod->buying_price }}</td>
<td>{{ $prod->selling_price }}</td>
<td>{{ $prod->weight}}</td>
@endforeach
products controller
public function index()
{
$products = products::all();
return view('products.products')->with('products', $products);
}
i also tried
public function index()
{
$products = products::all();
return view ('products.products',compact('products'));
}
route
Route::resource('products', 'ProductsController');
First you should make sure you didn't make any typos. As seen from the code you provided it should just work, as long as you have the products
model.
Normally how Laravel works is you have a route, in your case that's url.test/products
which is bound to some function in the ProductsController
. You haven't provided the method within the route. Maybe that could be it. Normally the route would look something similar to this:
Route::get('/projects', 'ProjectController@index')->name('projects');
Or in Laravel 8 it would look like this:
Route::get('/projects/all', [App\Http\Controllers\ProjectController::class, 'index'])->name('projects');
Then your index function within the controller should look similar to this. In that case there is nothing wrong with your code above
$projects = Project::all();
return view('projects', compact('projects'));
And you should be able to call $projects
within your view. Also try to see if $projects
is even full. Just do dd($projects)
within your controller so make sure it returns something.
I suggest you to go over the whole process again to see if you made any typos or mistakes that may cause this situation as your code above is perfectly fine except for not giving the right function in the route.
EDIT:
I can see now, you spelt [product] wrong. It is supposed to be [Product] as you’re calling the Product model.