Laravel预约表单提交后未跳转且数据未存入数据库求助
问题排查与解决方案
1. 先确认请求是否到达控制器
在appointment_store方法最开头添加调试代码,判断请求是否真的进入了控制器:
public function appointment_store(StoreAppointmentRequest $request) { dd("请求已到达控制器"); // 测试用,提交表单后看是否输出这句话 // ... 原代码 }
- 如果没有输出:
- 执行
php artisan route:list,确认front.appointment_store路由存在,请求方法为POST,且控制器方法路径正确。 - 检查页面源码,确认表单中是否渲染出CSRF令牌(
<input type="hidden" name="_token" value="xxx">),如果没有,检查@csrf标签是否写在表单内部,有没有语法错误。 - 用浏览器开发者工具查看网络请求:提交表单后,看请求的状态码和Form Data,确认请求地址是否正确,是否携带了
_token和表单字段。
- 执行
2. 检查验证规则是否拦截请求
Laravel的表单请求类(StoreAppointmentRequest)如果验证失败,会自动重定向回表单页面,且不会进入控制器方法逻辑。
- 在表单页面添加错误提示,查看是否有验证错误:
@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif - 暂时替换请求类为基础
Request,用控制器自带的validate方法测试,排除请求类的问题:use Illuminate\Http\Request; public function appointment_store(Request $request) { // 手动写验证规则,确保和表单字段匹配 $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email', 'phone' => 'required|string', // 其他表单字段的规则... ]); dd($validated); // 看是否能拿到验证后的数据 // ... 后续代码 }
3. 检查模型批量赋值权限
Appointment::create($validated)需要模型允许批量赋值,否则会静默失败(默认不报错):
打开App\Models\Appointment.php,添加$fillable属性列出所有需要存入数据库的字段:
class Appointment extends Model { use HasFactory; // 允许批量赋值的字段 protected $fillable = ['name', 'email', 'phone', 'date', 'time', ...]; // 或者设置$guarded为空数组,允许所有字段(注意安全,仅在开发阶段临时使用) // protected $guarded = []; }
4. 排查事务中的异常
事务内部如果出现异常,会自动回滚,但默认不会抛出错误信息,导致你看不到问题:
把事务换成try-catch捕获异常:
public function appointment_store(StoreAppointmentRequest $request) { try { DB::beginTransaction(); $validated = $request->validated(); $newAppointment = Appointment::create($validated); DB::commit(); dd($newAppointment); // 此时应该能看到创建的模型数据 } catch (\Exception $e) { DB::rollBack(); dd($e->getMessage()); // 输出具体错误信息,比如字段不存在、类型不匹配等 } return redirect()->route('front.index'); }
最终调整后的代码示例
确认所有问题修复后,代码可以恢复为:
public function appointment_store(StoreAppointmentRequest $request) { DB::transaction(function () use ($request) { $validated = $request->validated(); Appointment::create($validated); }); return redirect()->route('front.index'); }
内容的提问来源于stack exchange,提问作者Muhammad Agung Dzaki
相关产品推荐
相关产品推荐

