To paginate the data while using the Model's ::query() functionality, you need to assign the result of the paginate() method to the $query variable. Currently, the paginate() method is not being assigned to the $query variable, which is why the pagination meta data is missing from the response.
Here's the updated IndexController code:
class IndexController extends Controller
{
public function __invoke(ReadRequest $request)
{
$query = Company::query();
if ($request->has('sort') && !empty($request->sort)) {
$direction = 'orderBy';
if ($request->has('direction') && !empty($request->direction)) {
$direction = 'orderByDesc';
}
$query->{$direction}($request->sort);
}
if ($request->has('filter') && !empty($request->filter) && is_array($request->filter)) {
$columns = app(Company::class)->getFillable();
foreach ($request->filter as $filter => $value) {
if (in_array($filter, $columns)) {
$query->where($filter, 'LIKE', '%' . $value . '%');
}
}
}
if ($request->has('page') && !empty($request->page)) {
$pageLength = 50;
if ($request->has('length') && !empty($request->length)) {
$pageLength = $request->length;
}
$query = $query->paginate($pageLength, ['*'], 'page', $request->page);
}
return new CompanyCollection($query);
}
}
Notice that the result of the paginate() method is now being assigned to the $query variable. This will ensure that the pagination meta data is included in the response.
Also, make sure to remove the ->get() method call from the return statement in the IndexController. This is because the CompanyCollection class expects a LengthAwarePaginator instance, not a Collection instance.
Here's the updated CompanyCollection code:
class CompanyCollection extends ResourceCollection
{
public function toArray($request): array
{
return [
'data' => CompanyResource::collection($this->collection),
];
}
public function paginationInformation($request, $paginated, $default)
{
unset($default['links'], $default['meta']['links']);
return $default;
}
}
With these changes, the API should now properly paginate the data while still utilizing the Model's ::query() functionality.