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

如何在PHP数组中为subject字段设置默认值 附Laravel实际代码示例

解决方案

你代码里的核心问题是subject字段的数组赋值符号写错了,PHP关联数组的键值对应使用=>而不是=,修改后就能实现固定默认值的效果。

方案1:设置固定硬编码默认值(完全不需要从请求取subject)

直接修正语法错误即可,修改后的代码如下:

public function sendEmail(Request $request)
{
    $data = array(
        'name'      =>  $request->name,
        'phone'     =>  $request->phone,
        'subject'   =>  "New Client",
        'email'     =>  $request->email
    );

    Mail::to('info@example.com')->send(new ContactMail($data));
    return redirect()->route('home');
}

方案2:优先取请求中的subject,请求没有时再用默认值

如果后续有需要支持用户自定义邮件主题的需求,可以用$request->input()的第二个参数设置默认值,写法更灵活:

public function sendEmail(Request $request)
{
    $data = array(
        'name'      =>  $request->name,
        'phone'     =>  $request->phone,
        'subject'   =>  $request->input('subject', "New Client"),
        'email'     =>  $request->email
    );

    Mail::to('info@example.com')->send(new ContactMail($data));
    return redirect()->route('home');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:36:03