Laravel: 如何修改通知集合

Laravel: How to modify notifications collection

我有一个函数 returns database notifications of a user (the User model is Notifiable):

return $user->notifications()->get();

返回的结果是这样的:

[
    {
        "id": "5d6548d3-1f9b-4da5-b332-afbf428df775",
        "type": "Meysam\Notification\Classes\CommentCreated",
        "notifiable_id": 1,
        "notifiable_type": "RainLab\User\Models\User",
        "data": {
            "userId": 2,
            "commentId": 18
        },
        "read_at": null,
        "created_at": "2018-03-05 09:58:34",
        "updated_at": "2018-03-05 09:58:34"
    },
    {
        "id": "2e22e24e-a972-4a30-afeb-0049a40966a7",
        "type": "Meysam\Notification\Classes\CommentCreated",
        "notifiable_id": 1,
        "notifiable_type": "RainLab\User\Models\User",
        "data": {
            "userId": 3,
            "commentId": 17
        },
        "read_at": null,
        "created_at": "2018-03-05 09:38:38",
        "updated_at": "2018-03-05 09:38:38"
    }
]

在返回之前修改此集合的最佳方法是什么?例如,我想从对象中删除 "id" 字段,将 "type" 字段的值更改为 "CommentCreated",并向每个项目添加 "url", "username", "email", etc 等新字段。添加hiddenvisibleappend attributes to DatabaseNotification model class (if so, how)? Are API Resources在这里有用吗?

为Laravel 5.5+

使用API Resources.

对于 Laravel < 5.5

正如@linktoahref 所建议的,使用分形是个好主意。

根据定义,REF:http://fractal.thephpleague.com/

Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with JSON. Think of this as a view layer for your JSON/YAML/etc.

您可以使用分形将数据转换为适当的格式,在使用 laravel 时,最好为每个模型创建分形并在需要时使用。它可以接受一个模型并以适当的数据格式对每个字段和 return 执行转换。

spatie/laravel-fractal 是分形入门的好包。

如果您只想更改集合的 return 值,可以这样做:

$user->notifications()->get()->map(function($item) {
   unset($item['id']); //remove id
   $item['type'] = "CommentCreated"; //change the value of "type" field
   $item['url'] = "url content"; //add new data
   $item['username'] = "username content"; //add new data
   $item['email'] = "email content"; //add new data
   return $item;
});