0

我正在使用 Laravel 创建一个 API。

我创建了一个名为transaction. 我还创建了一个名为transactionresource.

我想将id列更改key为 API 中的列,并且我不希望 id 在 API 中显示;相反,键应该显示。

我的代码

class TransactionResource extends JsonResource
{
  
    public function toArray($request)
    {
        $array = parent::toArray($request);

        // set the new key with data
        $array['key'] = $array['id'];

        // unset the old key
        unset($array['id']);
        
        return $array;
    }
}

我收到此错误

{"success":false,"message":"Undefined array key \"id\""}
4

1 回答 1

2

您可以像这样返回自定义字段数组

public function toArray($request){
   return [
    'key' => $this->id,
    ...
];}

见文档

于 2022-01-26T16:18:35.383 回答