0
votes

i am trying to paginate a relationship result set by using a code very similar to this

<?php

class MainController extends Controller {

    public function show(Main $main)
    {
        $main = $main->with([
            'secondaryMorph' => function ($query) {
                $query->orderBy('ocurred_at');
                $query->paginate(50);
            }
        ])->first();

        return view('main.show')->with(compact('main'));
    }
}

But when this part of the view's code run a exception is thrown:

<td colspan="3">Mostrando {{ $secondary->count() }} de {{ $secondary->total() }}</td>
<td colspan="3">{{ $secondary->links() }}</td>

ErrorException (E_ERROR) Method Illuminate\Database\Eloquent\Collection::total does not exist.

How can i use eager loading with pagination?

1

1 Answers

0
votes

How about :

$main = $main->first();
$secondary = $main->secondaryMorph()->paginate();
return view('main.show')->with(compact('main','secondary'));

And then in blade :

<td colspan="3">Mostrando {{ $secondary->count() }} de {{ $secondary->total() }}</td>
<td colspan="3">{{ $secondary->links() }}</td>