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 this DB raw query and showing this error
Call to a member function paginate() on array
I just want how to implement laravel pagination with DB raw queries here is my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notice;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
class NoticeController extends Controller
{
public function index(){
$notices = DB::select('select
notices.id,notices.title,notices.body,notices.created_at,notices.updated_at,
users.name,departments.department_name
FROM notices
INNER JOIN users ON notices.user_id = users.id
INNER JOIN departments on users.dpt_id = departments.id
ORDER BY users.id DESC')->paginate(20);
$result = new Paginator($notices,2,1,[]);
return view('welcome')->with('allNotices', $notices);
}
}
->paginate(20), why are you usingnew Paginatoragain ? For anyone reading this, always try to understand what you are writing, literally read what you wrote, it has "semantic", there is no logic in paginating a paginator... And try to avoid raw queries as much as possible, ALWAYS use Models, and only useDBin when you have a really complex query and Eloquent will not solve it or would be harder to read than plainSQL.