1

I am working on a project in Laravel and using DB facade to run raw queries of sql. In my case I am using DB::select, problem is that pagination method is not working with it and showing this error

Call to a member function paginate() on array

How can I paginate this raw query? here is my code:

$que= DB::select("SELECT * FROM tbl_ourpeople INNER JOIN tbl_ourpeople_category ON
tbl_ourpeople.category = tbl_ourpeople_category.categoryId WHERE tbl_ourpeople.id>1");
return view('view',compact('que'));
Raj
  • 37
  • 8
  • Does this answer your question? [How to use pagination with laravel DB::select query](https://stackoverflow.com/questions/44090392/how-to-use-pagination-with-laravel-dbselect-query) – S. Farooq Dec 23 '21 at 10:41

2 Answers2

1

Try this:

$query = DB::table('tbl_ourpeople')
    ->join('tbl_ourpeople_category', 'tbl_ourpeople.category', '=', 'tbl_ourpeople_category.categoryId')
    ->where('tbl_ourpeople.id', '>', 1)
    ->paginate(15);
S. Farooq
  • 218
  • 5
  • 19
0

For pure raw query, you may use this way.

$perPage = $request->input("per_page", 10);
$page = $request->input("page", 1);
$skip = $page * $perPage;
if($take < 1) { $take = 1; }
if($skip < 0) { $skip = 0; }

$que = DB::select(DB::raw("SELECT * FROM tbl_ourpeople INNER JOIN tbl_ourpeople_category ON
tbl_ourpeople.category = tbl_ourpeople_category.categoryId WHERE tbl_ourpeople.id>1"));

$totalCount = $que->count();
$results = $que
    ->take($perPage)
    ->skip($skip)
    ->get();

$paginator = new \Illuminate\Pagination\LengthAwarePaginator($results, $totalCount, $take, $page);

return $paginator;
Nipun
  • 157
  • 5
  • This is not the feasible way. This will get the data as collection and then the pagination will be applied. It will take lot of memory when the data is huge – ManojKiran A Dec 23 '21 at 12:20
  • Yes I strongly agree with you. As he wanted to use purely raw query, so I provided him this solution. Best way is to use the eloquent way. – Nipun Dec 23 '21 at 14:20