iT邦幫忙

0

使用Laravel API Resource 問題

我專案上使用API Resource實做某一個資料的回傳, 最近分別實現show 和 index 的回傳

首先, 在show 部分的resource 我是這樣寫的

    public function toArray($request)
    {
        $this->giftCustomer->message = $this->giftMessages->gift_customer_message;
        
        $this->receiveCustomer->message = $this->giftMessages->receive_customer_message;

        return [
            .... (以上略)
            "gift"     => new Customer($this->giftCustomer),
            "receive"  => new Customer($this->receiveCustomer),
        ];
    }

而index 顯示列表時我得這樣

    public function toArray($request)
    {
        return [
             .... (以上略)
            "gift"     => collect(new Customer($this->giftCustomer))->merge(['message'=>$this->giftMessages->gift_customer_message]),
            "receive"  =>collect(new Customer($this->receiveCustomer))->merge(['message'=> $this->giftMessages->receive_customer_message])),
        ];

兩者其實customer 的部分都是一樣的

    public function toArray($request)
    {
        return [
            "id"        => $this->id,
            "account"   => $this->account,
            "nickname"  => $this->nickname,
            "message"   => $this->message
        ];
    }

其實我蠻喜歡上面show 部分的寫法,比較簡潔比較好看
但是index 我試過了卻無法正確顯示我要的message,
反而要在外層使用collect()->merge() 才能顯示我要的message

難道 Resouce::collection 和 new Resource() 有一些不一樣
所以才讓我在index 的部分沒辦法按照show 的寫法?

那麼, 我index的部分應該怎麼樣寫會比較好看?

也不知道怎麼打關鍵字,如果有建議的關鍵字可以丟給我好讓我去查看看

firecold iT邦新手 1 級 ‧ 2020-06-03 10:22:40 檢舉
laravel collection 本身有相關method叫toArray
你index直接collection->toArray()
應該就有東西了
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
通靈亡
iT邦高手 1 級 ‧ 2020-06-02 11:23:50
最佳解答

難道 Resouce::collection 和 new Resource() 有一些不一樣

前者是多個物件集合,後者是單一物件

https://blog.johnsonlu.org/laravel-eloquent-api-resources/

Collection
接下來問題來了,很多時候我們會取得資源的清單,比如說 SongModel::all(),直接使用 Resource 會出現錯誤訊息,因為丟進去的是一個 Collection ,並不是物件本身。

此時需要搭配 Resource::collection() 使用,它會將 Collection 中的所有 Model 物件自動套用 Resource 的格式。

我要發表回答

立即登入回答