Data is not shown in the view page. The view page is loaded, but the data isn’t passed.
As my first Laravel project, I could not find out the error? If anyone helps to sort it out it would be a great help.
CartController.php
use IlluminateHttpRequest;
use AppProduct;
use AppCategory;
class CartController extends Controller
{
public function index()
{
$product = Product::get();
return view ('cart')->with(compact('products'));
}
public function show($id)
{
$product = Product::find($id);
return view('cart')->with(compact('product'));
}
}
cart.blade.php
@foreach($product as $p)
<tr class="">
<td class="d-none d-md-table-cell">
<a href="#"><img class="img-fluid max-width-100 p-1 border border-color-1" src="{{asset('/storage/admin/'.$p ['prod_image_path'] ) }}" alt="Image Description"></a>
</td>
<td data-title="Product">
<a href="#" class="text-gray-90">{{ $p ['prod_name'] }}</a>
</td>
<td data-title="Price">
<span class="">LKR {{ $p ['prod_price'] }}.00</span>
</td>
</tr>
@endforeach
web.php
Route::get('/cart', 'CartController@index')->name('cart');
Route::get('/cart/{id}', 'CartController@show')->name('cart');
2
Answers
In your index method, your variable is named
$product
(singular), but you’re sendingproducts
(plural) to your view. This will therefore benull
in your view. Correct that spelling error and your index should be fine.For your show method, @TimLevis already pointed out that you’re retrieving a single instance of
Product
and not a collection.You can’t iterate over a single object unless there are array properties.
You can access your data in view like this {{$product->price}}