如何正确使用 API 资源 Resources 功能

文档中是这么介绍的

当构建 API 时,你往往需要一个转换层来联结你的 Eloquent 模型和实际返回给用户的 JSON 响应。Laravel 的资源类能够让你以更直观简便的方式将模型和模型集合转化成 JSON。

现在对返回一个资源集合的时候,不知道怎么处理,比如要返回一个用户列表,表中有10个字段,但是接口中只想返回其中 3 个字段,另外 7 个字段不需要返回。

那在 UserCollection 中怎么处理呢?因为 User 是个集合,不能直接用这种方式。

return [
    'name' => $this->name,
    'address' => $this->address,
    'tel' => $this->tel
];

可以用 $this->collection获得 User 集合,然后自己处理吗?类似这种

foreach ($this->collection as &$data) {
    unset($data['sort_field']);
    unset($data['deleted_at']);
    unset($data['created_at']);
    unset($data['updated_at']);
}

也可以用 Model 的 $hidden 属性来控制隐藏什么,但是如果用这种方式就不仅仅是接口数据隐藏了,直接查询的所有操作都会被隐藏。

以上应该都不是正确的玩法,你们怎么处理的呢?

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 6

不知到是不是用的这个是的话可以在toArray()中自定义的API 资源《Laravel 8 中文文档》
集合使用

$collection->only(['foo','bar'])
3年前 评论
风吹过有夏天的味道 (作者) 3年前

你可以试试在Resource中这么做

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ExampleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'filed1'                 => $this->filed1,
            'filed2'                   => $this->filed2
        ];
    }
}
3年前 评论
24K大白羊 (楼主) 3年前

可以使用withResponse方法处理一下,但是应该在查的时候指定一下字段才对呀~

    public function withResponse($request, $response)
    {
        $users = $response->getData(true);
        foreach ($users as $index =>$user){
            unset($users[$index]['field1'],$users[$index]['field2']);
        }
        $response->setData( $users );
    }
3年前 评论
24K大白羊 (楼主) 3年前

看一下文档, 官网说的集合resource反而不好用, 我用的这些年感受是这样.

# resouce
class VideoResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'            => $this->id,
            'name'            => $this->name,
            'relations'            => $this->whenLoaded('relations'),
        ];
    }
}
# 单个返回
return new VideoResource(Video::first());
# 返回集合
return VideoResource::collection(Video::with('relations')->get());
3年前 评论
seth-shi (作者) 3年前
24K大白羊 (楼主) 3年前
24K大白羊 (楼主) 3年前
随波逐流

Illuminate\Database\Eloquent\Model hidden 属性了解下

3年前 评论
24K大白羊 (楼主) 3年前
24K大白羊 (楼主) 3年前

可以自己写一个基类,来进行过滤。
具体操作:博客:在 Laravel 中动态 隐藏 / 显示 API 字段

3年前 评论
24K大白羊 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!