You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blade模板中根据按钮点击设置会话变量?

问题原因分析

你当前的写法存在核心逻辑错误:Blade模板中的@php代码是服务器在渲染页面时就执行完毕,而非用户点击按钮时触发。页面加载时,两个session()->put()会依次执行,最后button会话变量会被覆盖为cancel,因此无论点击哪个按钮,控制器读到的都是这个值。

正确实现方案

以下两种方案都能解决你的需求,按需选择:

方案1:通过按钮的name/value区分操作(推荐)

修改表单中的按钮,给它们添加name和value属性,提交后在控制器中判断点击的按钮:

<div class="mb-6">
    {{-- Submit按钮 --}}
    <button type="submit" name="action" value="submit" class="text-xl text-white bg-green-500 rounded-md py-2 px-4 hover:bg-black">Submit</button>
    {{-- Cancel按钮 --}}
    <button type="submit" name="action" value="cancel" class="text-xl text-white bg-black rounded-md py-2 px-4 hover:bg-red-300">Cancel</button>
</div>

然后在控制器的store方法中处理逻辑:

public function store(Request $request)
{
    // 判断是否点击Cancel
    if ($request->action === 'cancel') {
        return redirect('/')->with('message', 'Create() cancelled');
    }

    // Submit逻辑:验证+入库
    $validatedData = $request->validate([
        'reason_for_not_driving' => 'required|string',
    ]);

    NonDrivingReason::create($validatedData);

    return redirect('/')->with('message', 'Create was successful');
}

方案2:Cancel按钮直接跳转(更简洁)

如果Cancel不需要提交表单,直接取消操作并跳转首页,可将Cancel按钮改为普通按钮,用JavaScript实现跳转:

<div class="mb-6">
    <button type="submit" class="text-xl text-white bg-green-500 rounded-md py-2 px-4 hover:bg-black">Submit</button>
    <button type="button" onclick="window.location.href='/';" class="text-xl text-white bg-black rounded-md py-2 px-4 hover:bg-red-300">Cancel</button>
</div>

这种方式无需在控制器中额外处理Cancel逻辑,直接跳过表单提交流程。

内容的提问来源于stack exchange,提问作者Henry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:20:40