michalis's avatar

how to add pagination to this code

    $files = File::where('campaign_id', $id);

        if ($month = request('month')) {
            $files->whereMonth('created_at', Carbon::parse($month)->month);
        }

        if ($year = request('year')) {
            $files->whereYear('created_at', $year);
        }

        $files = $files->get()->sortByDesc('created_at');

I tried adding it on the first line but get

Too few arguments to function Illuminate\Support\Collection::get(), 0 passed, at least 1 expected

I tried adding it on the last line and get

Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
0 likes
7 replies
andreich1980's avatar
Level 50

get method returns a collection. I think you should paginate it before calling get.

$files = $files->latest('created_at')->paginate();
michalis's avatar

@ANDREICH1980 - if i do this

$files = $files->paginate(15)->get()->sortByDesc('created_at');

I get this error

Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in and at least 1 expected
devfrey's avatar

You should use @andreich1980's code. You cannot combine paginate() with get() as they both do something similar.

michalis's avatar

@ROBSTAR - I have, it did not mention that get() and paginate() do the same thing, or maybe I didnt understand

Please or to participate in this conversation.