在 Laravel 8 开发的预约系统中,我们经常会遇到这样的需求:页面上列出多个可预约的时段,每个时段用一个单选按钮表示,而已被预订的时段应该动态禁用,防止用户重复提交。实现的核心思路是,后端查询已预订时段并传递给视图,前端根据数据禁用对应单选按钮。

一、控制器中查询已预订时段
假设我们有一个 appointments 表,里面记录了日期和时段标识(如 morning、afternoon)。在控制器里,我们可以先取出某天已被占用的时段。
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
class AppointmentController extends Controller
{
public function create(Request $request)
{
$date = $request->input('date', date('Y-m-d'));
// 查询该日期下已预订的时段
$booked = DB::table('appointments')
->where('date', $date)
->pluck('slot')
->toArray();
// 所有可选时段
$slots = [
'morning' => '上午 09:00-12:00',
'afternoon' => '下午 14:00-17:00',
'evening' => '晚上 19:00-21:00'
];
return view('appointments.create', compact('slots', 'booked', 'date'));
}
}
二、Blade 模板中动态渲染单选按钮
在视图文件里,我们遍历时段数组,并判断当前时段是否出现在已预订数组中,如果是则添加 disabled 属性。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>预约时段</title>
</head>
<body>
<h3>选择预约时段({{ $date }})</h3>
<form method="POST" action="/appointments">
@csrf
@foreach ($slots as $key => $label)
<label>
<input type="radio" name="slot" value="{{ $key }}"
@if(in_array($key, $booked)) disabled @endif>
{{ $label }}
@if(in_array($key, $booked))
<em>(已预订)</em>
@endif
</label>
<br>
@endforeach
<button type="submit">提交预约</button>
</form>
</body>
</html>
三、用 JavaScript 增强交互(可选)
如果时段是异步加载的,也可以用 JS 动态禁用。下面示例展示拿到 booked 数组后如何操作。
// 假设从接口拿到已预订时段
let booked = ['afternoon'];
document.querySelectorAll('input[name="slot"]').forEach(function (el) {
if (booked.indexOf(el.value) !== -1) {
el.disabled = true;
let em = document.createElement('em');
em.textContent = '(已预订)';
el.parentNode.appendChild(em);
}
});
四、小结
通过以上方式,我们就能在 Laravel 8 中轻松实现动态禁用已预订预约时段的单选按钮。核心就是后端提供准确数据,前端或模板做条件判断,既简单又可靠。