Home > Software engineering >  How can i paginate this raw query?
How can i paginate this raw query?

Time:12-24

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'));

CodePudding user response:

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);

CodePudding user response:

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;
  • Related