Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method paginate does not exist. in laravel after conversion to object

I'm getting this error for pagination

Method paginate does not exist.

$allTodaysJob = \DB::select(\DB::raw('select * from `new_job` WHERE DATE(created_at) = DATE(CURRENT_TIMESTAMP())'));

$collection = collect($allTodaysJob)->paginate(10);

return view('common_status',['data'=>$collection]); 

Please help me to solve this issue.


2 Answers

Paginate works with Eloquent model. Make a model and then If you use model you can do something like this with eloquent:

$allTodaysJob = ModelName::where('created_at', DATE(CURRENT_TIMESTAMP())->get()->paginate(10); 

Or if you want to order it by latest:

$allTodaysJob = ModelName::where('created_at', DATE(CURRENT_TIMESTAMP())->latest()->paginate(10); 

But if it you want to use raw query you can make a custom pagination method in the current class. first, you make an array, then you pass that array to the paginator method like this code below:

this is the pagination method:

 protected function paginate($items,$perPage,$request)
    {

        $page = Input::get('page', 1); // Get the current page or default to 1

        $offset = ($page * $perPage) - $perPage;

        return new LengthAwarePaginator(
            array_slice($items, $offset, $perPage, true),
            count($items), $perPage, $page,
            ['path' => $request->url(), 'query' => $request->query()]
        );
    }

Then you can call the paginate method after you select data from the database, I would recomend to do it with raw method instead of select:

$allTodaysJob = \DB::raw('select * from `new_job` WHERE DATE(created_at) = DATE(CURRENT_TIMESTAMP())')->get();

$allTodaysJob = $this->paginate($allTodaysJob,10,$request);

Note that you should pass the Request $request to the index method and then use it in the pagination.Because from that request to specific page through pagination link laravel pagination know which items to select to show in your view.

Hope it would help!

like image 52
Salar Bahador Avatar answered Oct 14 '25 07:10

Salar Bahador


In my opinion it should go that way:

 $collection = collect($allTodaysJob)->get()->toArray()->paginate(10);
like image 27
Adam Kozlowski Avatar answered Oct 14 '25 07:10

Adam Kozlowski