Skip to content

Commit

Permalink
Customize type column in database notifications using databaseType me…
Browse files Browse the repository at this point in the history
…thod.
  • Loading branch information
mvaliolahi committed Nov 29, 2021
1 parent 78637dc commit cd9b283
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Illuminate/Notifications/Channels/DatabaseChannel.php
Expand Up @@ -55,9 +55,24 @@ protected function buildPayload($notifiable, Notification $notification)
{
return [
'id' => $notification->id,
'type' => get_class($notification),
'type' => $this->chooseType($notification),
'data' => $this->getData($notifiable, $notification),
'read_at' => null,
];
}

/**
* Use databaseType method or the notification class name for the type column.
*
* @param mixed $notification
* @return string
*/
private function chooseType($notification)
{
if (method_exists($notification, 'databaseType')) {
return $notification->databaseType();
}

return get_class($notification);
}
}
31 changes: 31 additions & 0 deletions tests/Notifications/NotificationDatabaseChannelTest.php
Expand Up @@ -49,6 +49,24 @@ public function testCorrectPayloadIsSentToDatabase()
$channel = new ExtendedDatabaseChannel;
$channel->send($notifiable, $notification);
}

public function testCustomizeTypeIsSentToDatabase()
{
$notification = new NotificationDatabaseChannelCustomizeTypeTestNotification;
$notification->id = 1;
$notifiable = m::mock();

$notifiable->shouldReceive('routeNotificationFor->create')->with([
'id' => 1,
'type' => 'MONTHLY',
'data' => ['invoice_id' => 1],
'read_at' => null,
'something' => 'else',
]);

$channel = new ExtendedDatabaseChannel;
$channel->send($notifiable, $notification);
}
}

class NotificationDatabaseChannelTestNotification extends Notification
Expand All @@ -59,6 +77,19 @@ public function toDatabase($notifiable)
}
}

class NotificationDatabaseChannelCustomizeTypeTestNotification extends Notification
{
public function toDatabase($notifiable)
{
return new DatabaseMessage(['invoice_id' => 1]);
}

public function databaseType()
{
return 'MONTHLY';
}
}

class ExtendedDatabaseChannel extends DatabaseChannel
{
protected function buildPayload($notifiable, Notification $notification)
Expand Down

0 comments on commit cd9b283

Please sign in to comment.