0

I have a Laravel API call, and I want to paginate the result, but can't seem to find the way that works. My call looks like this:

public function index(Request $request){
    $per_page = $request->input('per_page');

    if(!$per_page)
        $per_page=20;

    $creditos = Prestacion::all();
    $creditos = $creditos->paginate($per_page);
    return $this->collection($creditos, new PrestacionTransformer);
}

This returns the error:

"Method Illuminate\Database\Eloquent\Collection::paginate does not exist."

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71

1 Answers1

1

This is due to the fact that you are running the query before paginating it. Check this line:

$creditos = Prestacion::all();

The all() method executes the query. This means that $creditos is now an instance of Collection instead of QueryBuilder. This is the reason why. the paginate() method doesn't exist in the class.

You should do instead:

$creditos = Prestacion::paginate();

return $this->collection($creditos, new PrestacionTransformer);

That should work for you.

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
  • Ok, I think I get it, but now I got the error "Argument 1 passed to Dingo\\Api\\Http\\Response\\Factory::collection() must be an instance of Illuminate\\Support\\Collection, instance of Illuminate\\Pagination\\LengthAwarePaginator given" – Iván Flores Vázquez Jun 08 '21 at 23:53
  • @IvánFloresVázquez, Try using `return $this->collection(collect(Prestacion::all()), new PrestacionTransformer);` – steven7mwesigwa Jun 09 '21 at 00:21
  • @steven7mwesigwa Now it says "Unable to find bound transformer for \"App\\Models\\PrestamosCreditos\\Prestacion\" class". And, wouldn't that return the whole collection, and not it paginated? – Iván Flores Vázquez Jun 09 '21 at 16:30