Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify notification attributes via toArray / toDatabase function in Laravel?

Laravel's Notification allows saving data in a notifications table using toArray or toDatabase. But the documentation doesn't clarify 2 things.

  1. What is the difference between toArray() and toDatabase() when it comes to storing data in the notifications table?

  2. I have added an additional attribute (link) to notifications table, but when I do:

    public function toDatabase() {
        return [
            'data'=>'My Data',
            'link'=>'My Link'
        ];
    }
    

I end up getting the array serialized under the data attribute. What is the proper way to save the attributes using the toArray() or toDatabase() function?

like image 341
Artur Grigio Avatar asked Oct 18 '25 12:10

Artur Grigio


1 Answers

1) The method used is determined by your via() return array:

return ['mail', 'database', 'broadcast'];

When you ONLY use the toArray it will use that single data array for the Database and Broadcast notification. If you wish to define separate arrays for each then you can define the toDatabase() and toBroadcast() methods.

2) As notifications is built into the core of Laravel - there is no easy way to alter its Model - ie add that addition fillable field. Notifications wants you to add that addition fields to the "data" array. Which by the way can still be accessed via:

$notification->my_custom_data_value
like image 140
Andrew Avatar answered Oct 21 '25 08:10

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!