问题
I am trying to create relations, and when notifications are fetched via $user->unreadNotifications
I want to control which fields are shown, and fetch the relations. I cannot figure out where to do this.
I did the following:
php artisan notifications:table
php artisan make:migration add_relations_to_notifications_table
In this new migration I added
requester_id
.$table->integer('requester_id')->unsigned()->nullable(); $table->foreign('requester_id')->references('id')->on('users')->onDelete('cascade');
php migrate
php artisan make:notification AnInviteWasRequested
Then in AnInviteWasRequested
I removed the toArray
and replaced it with toDatabase
:
public function toDatabase($notifiable)
{
return [
'requester_id' => Auth::guard('api')->user()->id
];
}
However this does not set the requester_id
field, it just put json into the data
column that looks like this: {"requester_id":1}
.
Is there anyway to get this to update the requester_id
field instead of updating data
?
And also is it possible somewhere, like a Model file (not in vendor
dir) to control which fields are displayed when $user->unreadNotifications
is done?
回答1:
Actually to define which field to show/save, and then you need it to display, you only need to modify the toDatabase
method. Example:
public function toDatabase($notifiable)
{
$user = Auth::guard('api')->user();
return [
'requester_id' => $user->id,
'requester_name' => $user->name,
// and more data that you need to show
];
}
So for relational data or any other data, just define it inside this method. Hope it helps. :)
来源:https://stackoverflow.com/questions/48259987/how-to-add-relations-to-notifications-and-get-the-related-data-in-json