Laravel中修改JSON输出:移除分页字段仅返回数据列表
Laravel 控制器返回仅用户数据的JSON列表
问题场景
使用paginate()查询用户数据时,返回的JSON包含current_page、first_page_url等分页字段,但需求是仅返回data中的用户数据列表。
当前控制器代码
class CustomerController extends Controller { public function index() { $customers=Customer::paginate(10); return response()->json([ 'data'=> $customers ]); } }
当前输出(含分页字段)
[ { "current_page": 1, "data": [ { "_id": "6580f69587f0f77a14091c22", "email": "janzboy@gmail.com", "first_name": "Janz", "last_name": "Boy", "password": "1995" } ], "first_page_url": "http://localhost:8000/api/customer?page=1" } ]
期望输出(仅用户数据)
[ { "_id": "6580f69587f0f77a14091c22", "email": "janzboy@gmail.com", "first_name": "Janz", "last_name": "Boy", "password": "1995" } ]
解决方案
修改控制器代码,直接获取分页结果中的纯数据集合返回:
方法一:使用items()方法
class CustomerController extends Controller { public function index() { $customers = Customer::paginate(10); // 获取当前页的用户数据列表 return response()->json($customers->items()); } }
方法二:直接访问data属性
class CustomerController extends Controller { public function index() { $customers = Customer::paginate(10); return response()->json($customers->data); } }
说明
Laravel的paginate()返回的是LengthAwarePaginator实例,items()方法和data属性都可以直接获取当前页的模型数据集合,返回后就只会输出用户数据列表,不会携带分页相关字段。
内容的提问来源于stack exchange,提问作者Januar
相关产品推荐
相关产品推荐

