我不能为我的生活,遍历我的模型来显示我的数据库表。
这是我提出请求的地方。
public function index()
{
$vehicles = vehicle::all();
return view('vehicles', compact('vehicles'));
}
以下是我的观点:
<table class ="vehicles-table">
<tr>
<td> id</td>
<td> First Name</td>
<td> Last Name</td>
<td> Contact Number</td>
<td> email</td>
<td> manufacturer</td>
<td> type</td>
<td> year</td>
<td> colour</td>
<td> mileage</td>
</tr>
@foreach($vehicles as $vehicle)
@if($vehicle->soft_del == 1)
@continue
@endif
<tr>
@foreach($vehicle as $info)
@if($loop->iteration >= 11)
@break
@endif
<td> {{ $info }} </td>
@endforeach
</tr>
@endforeach
Even though I get this in tinker
如何有效地遍历我的车辆?
答案 0 :(得分:0)
看起来你不仅要尝试遍历每辆车,还要尝试每辆车的每个领域(这不是正确的方法)。你应该明确地调用每个字段。
<table class ="vehicles-table">
<tr>
<td> id</td>
<td> First Name</td>
<td> Last Name</td>
<td> Contact Number</td>
<td> email</td>
<td> manufacturer</td>
<td> type</td>
<td> year</td>
<td> colour</td>
<td> mileage</td>
</tr>
@foreach($vehicles as $vehicle)
@if($vehicle->soft_del == 1)
@continue
@endif
<tr>
<td> {{ $vehicle->id }} </td>
<td> {{ $vehicle->first_name}} </td>
<td> {{ $vehicle->last_name}} </td>
<td> {{ $vehicle->contact_number }} </td>
<td> {{ $vehicle->email }} </td>
<td> {{ $vehicle->manufacturer }} </td>
<td> {{ $vehicle->type }} </td>
<td> {{ $vehicle->year }} </td>
<td> {{ $vehicle->colour }} </td>
<td> {{ $vehicle->mileage }} </td>
<td> {{ $vehicle->id }} </td>
</tr>
@endforeach
否则,如果您真的想要迭代模型,请使用$ vehicle-&gt; toArray()。
@foreach($vehicles as $vehicle)
@if($vehicle->soft_del == 1)
@continue
@endif
<tr>
@foreach($vehicle->toArray() as $info)
@if($loop->iteration >= 11)
@break
@endif
<td> {{ $info }} </td>
@endforeach
</tr>
@endforeach
***代码未经测试
答案 1 :(得分:0)
如何在另一个foreach循环中实现foreach循环,这是错误的。
第一个正确完成。当你打电话给foreach($ vehicles as vehicle)时,它需要$ vehicles数组并一次遍历一个Vehicle模型。
第二个循环是发生错误的地方。调用foreach($ vehicle作为$ info)是错误的,因为当它是车辆模型时,你将车辆视为一个阵列。将其更改为此应该有效:
@foreach( $vehicle->toArray() as $key => $value )
<td> {{ $value }} </td>
@endforeach