By default, Laravel transforms the response into JSON if you just return a Model or Eloquent Collection.
Example with Pagination
public function index()
{
return User::paginate();
}
Will return:
{
"current_page": 1,
"data": [
{
"id": 1,
"name": "Prof. Marcos Ratke",
"email": "[email protected]",
"email_verified_at": "2023-01-04T12:26:19.000000Z",
"created_at": "2023-01-04T12:26:20.000000Z",
"updated_at": "2023-01-04T12:26:20.000000Z"
},
{
"id": 2,
"name": "Sincere Casper",
"email": "[email protected]",
"email_verified_at": "2023-01-04T12:26:19.000000Z",
"created_at": "2023-01-04T12:26:20.000000Z",
"updated_at": "2023-01-04T12:26:20.000000Z"
},
// ... other users
],
"first_page_url": "http://laravel.test/api/users?page=1",
"from": 1,
"last_page": 2,
"last_page_url": "http://laravel.test/api/users?page=2",
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
{
"url": "http://laravel.test/api/users?page=1",
"label": "1",
"active": true
},
{
"url": "http://laravel.test/api/users?page=2",
"label": "2",
"active": false
},
{
"url": "http://laravel.test/api/users?page=2",
"label": "Next »",
"active": false
}
],
"next_page_url": "http://laravel.test/api/users?page=2",
"path": "http://laravel.test/api/users",
"per_page": 15,
"prev_page_url": null,
"to": 15,
"total": 20
}
As you can see, the users are wrapped in data, and the main JSON contains more data about pages.
I've just written a quick tutorial for it, for future reference.