我想在表格的每一行中插入一個按鈕,當我點擊這個按鈕時,它會使用 Laravel 將我重定向到另一個頁面,其中包含單個表格行的資料我該怎么做?
這是我的表格:
<html>
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">USERNAME</th>
<th scope="col">MAC ADDRESS</th>
</tr>
</thead>
<tbody>
@foreach ($data as $item)
<tr>
<th scope="row">{{$item->id}}</th>
<td>{{$item->username}}</td>
<td>{{$item->mac_addr}}</td>
<td>
<form action="{{url('singleDevice')}}" method="get">
<button class="btn btn-primary" type="submit">Select</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
這是我的控制器:
class DeviceController extends Controller
{
public function index()
{
$data=Device::all();
return view('device', compact("data"));
}
public function create()
{
return view('registrationDevice');
}
public function store(Request $request)
{
$input = new Device;
//On left field name in DB and on right field name in Form/view
$input -> username = $request->username;
$input -> mac_addr = $request->mac_address;
$input->save();
return redirect('registrationDevice')->with('message', 'DATA SAVED');
}
public function show(Device $device)
{
return view('singleDevice');
}
}
提前致謝
uj5u.com熱心網友回復:
改變你的形式,如:
<tbody>
@foreach ($data as $item)
<tr>
<th scope="row">{{$item->id}}</th>
<td>{{$item->username}}</td>
<td>{{$item->mac_addr}}</td>
<td>
<a href="{{ url('/singleDevice/'.$item->id) }}" class="btn btn-primary">Select</a>
</td>
</tr>
@endforeach
</tbody>
如果要使用路由名稱,可以通過以下方式更改:
<td>
<a href="{{ route('show', ['deviceID' => $item->id]) }}" class="btn btn-primary">Select</a>
</td>
改變你的路線,如:
Route::get('/singleDevice/{deviceID}', [DeviceController::class, 'show'])->name('show');
更改show控制器的功能,例如:
public function show($deviceID)
{
$device = Device::firstWhere('id', $deviceID);
return view('singleDevice', compact("device"));
}
uj5u.com熱心網友回復:
為什么需要表格?使用鏈接
<form action="{{url('singleDevice')}}" method="get">
<button class="btn btn-primary" type="submit">Select</button>
</form>
用。。。來代替
<a href="{{ route('show', ['device' => $item->id]) }}" class="btn btn-primary">Select</a>
并將路由器中的 URL 配置為 /singleDevice/{device}
Route::get('/singleDevice/{device}', [DeviceController::class, 'show'])->name('show');
uj5u.com熱心網友回復:
您也可以使用它,因為您已經在代碼中使用了表單
<form action="{{ route('show', $item->id) }}" method="get">
<button class="btn btn-primary" type="submit">Select</button>
</form>
public function show(Device $device)
{
return view('singleDevice');
}
對于路線,您可以通過$device:
Route::get('/singleDevice/{$device}', [DeviceController::class, 'show'])->name('show');
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316595.html
