Laravel:将自定义数据添加到资源

时间:2020-09-29 05:44:36

标签: laravel

首先,我使用这一行代码通过翻译者的ID来获取翻译器

$translator = Translator::where('id', $translator_id)->first();

然后我通过以下代码向他发送通知:

$response = Http::withHeaders([
            'Authorization' => 'key=myKey',
            'Content-Type' => 'application/json'
        ])->post('https://fcm.googleapis.com/fcm/send', [
            "notification" => [
                "title" => "title",
                "body" => "body",
            ],
            "data" => [
                "title" => "title",
                "body" => "body",
            ],
            "to" => $token,
        ]);

一切正常,但是我的问题是,当我返回TranslatorResource时,我想向其添加通知响应,因此我需要在控制器中执行此操作

$resource = new TranslatorResource($translator);
        $resource->notif = $response;
        return $resource;

TranslatorResource中,我有以下代码:

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'phone' => $this->phone,
            'cv' => $this->cv,
            'specialization' => $this->specialization,
            'tr_languages' => $this->tr_languages,
            'all_languages' => $this->all_languages,
            'isVerified' => $this->isVerified == 0 ? false : true,
            'isActive' => $this->isActive == 0 ? false : true,
            'completed_orders' => $this->completed_orders,
            'canceled_orders' => $this->canceled_orders,
            'rejected_orders' => $this->rejected_orders,
            'current_orders' => $this->current_orders,
            'isTranslator' => true,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }

但是我只获取资源中指定的数据,没有添加notif键,有人知道如何在返回数据时将其添加到资源中吗?

1 个答案:

答案 0 :(得分:0)

您可以使用laravel提供的additional方法。

return (new TranslatorResource($translator))->additional(['notif ' => $response]);

参考:Eloquent: API Resources

您可以找到Adding Meta Data When Constructing Resources部分。