حسین اچ
حسین اچ

Reputation: 107

use pagination in laravel api resource in laravel

I want to use pagination after getting my data from api resource But the server responds:

 Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
  public function index(Request $request )
    {
        $perPage=$request->per_page;
        return response()->json(['user'=>UserResource::collection(User::with('roles')->get()->pagination($perPage))],200);
    }

Upvotes: 0

Views: 492

Answers (2)

حسین اچ
حسین اچ

Reputation: 107

        return response()->json(['user'=>UserResource::collection(User::paginate($perPage))],200);

this is worked correctly ! 100% ok

Upvotes: 0

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

You don't have to call paginate on get function

Just

public function index(Request $request ) {
    $perPage=$request->per_page;
    return response()->json(['user'=>UserResource::collection(User::with('roles')->pagination($perPage))],200);
}

Even Better

public function index(Request $request ) {
    $perPage=$request->per_page;
    return new UserCollection(User::with('roles')->paginate($perPage));
}

Upvotes: 2

Related Questions