How to use paginator in Laravel API resources by default
In Laravel API Resources, facilitating pagination is seamless. Bypassing the Paginator instance to the Resource, Laravel adeptly manages pagination, streamlining the process. Below is a demonstration of how Laravel effortlessly handles this task for you.
<? php
namespace App\Http\Controllers;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
return UserResource::collection(User::paginate());
/*
The response will have the following structure
{
data: [ ... ],
Links: { ... },
meta: {
current_page: 1,
from: 1,
Last_page: 1,
Links: [ ... ],
path: "https://laravel10.test/users",
per_page: 15,
to: 10,
total: 10
}
}
*/
}
}