I’m attempting to save my notifications to the notification database table.
However I keep getting the following error:
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 notifications are working fine but database keeps giving errors.
The way I solved this was by adding json encode around the toArray() function but this doesn’t seem right to me, as normally laravel should do this encoding by itself, I don’t understand why the data attribute is not encoding properly.
public function toArray(object $notifiable)
{
return [
'message' => $this->data->name,
];
}
// Updated version
public function toArray(object $notifiable): string
{
return json_encode([
'message' => $this->data->name,
]);
}
I created my table using 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();
});
I’m also including Notifiable
on my user model.