Home > Net >  Laravel: Undefined variable in @foreach
Laravel: Undefined variable in @foreach

Time:12-13

I want to display order_details table on web, but @foreach loop says Undefined variable $order_details Here is my @foreach loop

@foreach($order_details as $order_detail)
<tr>
<td>{{$order_detail->product_id}}</td>
<td>{{$order_detail->name}}</td>
<td>{{$order_detail->phone}}</td>
</tr>
@endforeach

My order controller contains this:

   public function show(Order $order)
{
$order_details=Order_Detail::all();
return view('orders.index',['order_details' => $order_details]);
}

CodePudding user response:

What I noticed in your code is that you might be expecting an answer in another place while your code is running somewhere else. First of all, you are writing a show(Order $order) function that collects parameters, while you are outputting it in the index page, so where you are calling the show function will expect a parameter, while the index will not expect a parameter

CodePudding user response:

Okay If I am not wrong your Model name is Order.php but if not then good use your Model name in the controller to fetch all details

public function show()
{
  $order_details=Order::all();
  return view('posts.index',compact('order_details'));
}

view not needed to change

@foreach($order_details as $order_detail)
<tr>
 <td>{{$order_detail->product_id}}</td>
 <td>{{$order_detail->name}}</td>
 <td>{{$order_detail->phone}}</td>
</tr>
@endforeach

Please clear your routes

php artisan route:cache
  • Related