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

Laravel 11数据库通知数据编码异常问题求助

Laravel数据库通知保存失败:数组转字符串错误

我尝试把通知保存到notifications数据表,代码如下:

$n = new testNotification($company);
$user->notify($n);

但一直报以下错误:

Array to string conversion
INSERT INTO
notifications (
id,
type,
data,
read_at,
notifiable_id,
notifiable_type,
updated_at,
created_at
)
VALUES
(
6242fed0 - db16 -4864 - bd68 - 853bc2ada748,
App \ Notifications \ testNotification,
?,
?,
1,
App \ Models \ USER,
2024 -07 -24 12: 00: 13,
2024 -07 -24 12: 00: 13
)

Slack通知功能正常,但数据库通知始终报错。我通过在toArray()方法里用json_encode包裹返回值解决了问题,但这不符合Laravel默认行为——Laravel本该自动完成编码,我搞不懂data字段为什么无法正常编码。

原toArray方法:

public function toArray(object $notifiable)
{
    return [
        'message' => $this->data->name,
    ];
}

修改后版本:

public function toArray(object $notifiable): string
{
    return json_encode([
        'message' => $this->data->name,
    ]);
}

我用php artisan make:notifications-table创建的数据表,迁移代码如下:

/**
 * Run the migrations.
 */
public function up(): void
{
    Schema::create('notifications', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('type');
        $table->morphs('notifiable');
        $table->text('data'); // Ensure this is TEXT or LONGTEXT
        $table->timestamp('read_at')->nullable();
        $table->timestamps();
    });
}

另外,我的User模型已经引入了Notifiable特质。


排查与解决思路

  • 检查$this->data->name的数据类型:如果$this->data->name是数组/对象而非字符串,会导致toArray返回的数组包含不可直接序列化的元素,触发转字符串错误。可以先打印$this->data的类型和内容,确认是否有异常结构。
  • 确认Laravel版本兼容性:不同版本的Laravel对通知data字段的序列化逻辑有差异,确保你的版本要求toArray返回数组(默认行为)而非字符串。
  • 排查自定义逻辑干扰:如果项目重写了DatabaseNotification模型或自定义了通知存储逻辑,可能破坏了Laravel默认的JSON序列化流程。
  • 清理缓存:执行php artisan cache:clear和composer dump-autoload,避免类加载或配置缓存导致的异常。

正确修复方式

不要修改toArray的返回类型,保持它返回数组。问题大概率出在$this->data->name的取值上:

  • 如果$this->data是Eloquent模型,确保name属性是字符串类型,而非关系对象或数组;
  • 如果$this->data是自定义数据结构,检查是否实现了正确的序列化接口,或赋值时确保name是可直接转为字符串的类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:36:03