按钮在表行重定向到另一个页面与行的数据在Laravel



我想在表的每一行插入一个按钮,当我单击此按钮时,它将我重定向到使用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');
}
}

Thanks in advance

把你的表单改成:

<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"));
}

为什么需要表单?使用链接

<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');

你也可以在你的代码中使用form

<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');
}

For Route you can pass$device:

Route::get('/singleDevice/{$device}', [DeviceController::class, 'show'])->name('show');

最新更新