Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bork's avatar
Level 1

Undefined variable in foreach in view.

Hello, I'm pretty new to laravel and i was experimenting with some basic CRUD. After trying to pass data to my view and into a table it said my variables are undefined, even if i tried each one separately.

ProductController.php

	public function index(){
    $products = Product::all();
    return view('products.index', ['products' => $products]);

}

index.blade.php

	<table border="1">
		<tr>
			<th>Id</th>
			<th>Brand name</th>
			<th>Product name</th>
			<th>Quantity</th>
			<th>Description</th>
			<th>Price</th>
		</tr>
		@foreach($products as $product)
		<tr>
			<td>{{$product->$id}}</td>
			<td>{{$product->$productBrand}}</td>
			<td>{{$product->$productName}}</td>
			<td>{{$product->$quantity}}</td>
			<td>{{$product->$description}}</td>
			<td>{{$product->$price}}</td>
		</tr>
		@endforeach
	</table>

I have tried doing 'dd($products)' both in the view and inside the controller, which did work and show me the data. So to me it looks like it at least arrives at the view. Even if i do {{$product}} inside the foreach, i get data:

{"id":4,"productBrand":"Apple Brand","productName":"Apple","quantity":50,"description":"Red Apple","price":"1.00","created_at":"2023-06-21T00:09:31.000000Z","updated_at":"2023-06-21T00:09:31.000000Z"}

0 likes
5 replies
webrobert's avatar

You mean $product->productNam not $product->$productNam

1 like
bork's avatar
Level 1

@webrobert Ah thanks! It was rather late so my slow brain probably just didn't notice.

arsalan_ahmed_siddique's avatar

In PhP we use $ sign for variables and you are using this sign with key of an object, use this

<td>{{$product->id}}</td>
<td>{{$product->productBrand}}</td>
<td>{{$product->productName}}</td>
<td>{{$product->quantity}}</td>
<td>{{$product->description}}</td>
<td>{{$product->price}}</td>
1 like
krisi_gjika's avatar

$product->$productNam is attempting to get a property from $product named after the value of $productNam, but a variable $productNam does not exist.

Please or to participate in this conversation.