我有一个 html 表,其中包含我数据库中的汽车列表,我希望在表中选择一行来打开一个引导模式,其中包含来自数据库表的正确 ID。 “更改状态”按钮打开显示汽车、车牌和状态的模式。但它只获取最新的 id。当我将模态移动到顶部时,它会获取表中的第一个 id。我对如何解决这个问题感到困惑。
这是我的 html 代码:
@if (isset($results))
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead>
<tr>
<th width="15%"></th>
<th>#</th>
<th>Numberplate</th>
<th>Status</th>
<th>Added</th>
<th>Changed</th>
<th>Change</th>
</tr>
</thead>
@foreach ($results as $result)
<tbody>
<tr>
<td></td>
<td>{{ $result->id }}</td>
<td>{{ $result->LicencePlate }}</td>
<td>{{ $result->Status }}</td>
<td>{{ $result->created_at }}</td>
<td>{{ $result->updated_at }}</td>
<td>
<button type="button" class="btn btn-secondary btn-sm" style="background-color: #000; color: #FFF;" data-toggle="modal" data-target="#myModal">Change Status</button>
</td>
</tr>
</tbody>
@endforeach
@endif
</table>
</div>
@if (isset($cars))
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead>
<tr>
<th width="15%"></th>
<th>#</th>
<th>Numberplate</th>
<th>Status</th>
<th>Added</th>
<th>Changed</th>
<th>Change</th>
</tr>
</thead>
@foreach ($cars as $car)
<tbody>
<tr>
<td></td>
<td>{{ $car->id }}</td>
<td>{{ $car->LicencePlate }}</td>
<td>{{ $car->Status }}</td>
<td>{{ $car->created_at }}</td>
<td>{{ $car->updated_at }}</td>
<td>
<button type="button" class="btn btn-secondary btn-sm" style="background-color: #000; color: #FFF;" data-toggle="modal" data-target="#myModal">Change Status</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</div>
</div>
</div>
@if (isset($cars))
@foreach ($cars as $car)
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<p>ID: {{ $car->id }}</p>
<p>Numberplate: {{ $car->LicencePlate }}</p>
<p>Status: {{ $car->Status }}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
@endforeach
@endif
不完全确定我的 Controller 中是否有特殊方法,或者您是否需要查看我的模型。如果是这样,我可以编辑这个问题。
最佳答案
现在,在您的情况下,模态 ID #myModal
在循环内重复。像这样更改模态 ID 和按钮 ID,
<button type="button" class="btn btn-secondary btn-sm" style="background-color: #000; color: #FFF;" data-toggle="modal" data-target="#myModal_{{ $car->id }}">Change Status</button>
和模态
<div class="modal fade" id="myModal_{{ $car->id }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<!--Modal content here -->
<div>
仅供引用:对按钮和模式使用单一循环。
关于php - Laravel 5 从表中获取正确的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35792548/