Pagination Error

I’m trying to add pagination within a section of my Livewire view but I receive this error:

Method Illuminate\Database\Eloquent\Collection::links does not exist

Here is the render function of my controller with the paginate function:

public function render()

    {

        return view('livewire.contactshow')

        ->withContactnotes($this->contacts->contactnotes()->paginate(5));

    }

Here is my view attempting to show the pagination links:

{{ $this->contacts->contactnotes->links() }}

I obviously have this written to use the relationship between contacts and contactnotes, but that might not work with the paginate() syntax, but I’m not sure how to change it.

Your paginated variable in the view is $contactnotes (because you used withContactnotes)

Therefore you need to use

{{ $contactnotes->links() }}

When I use that code, I get a new error:

Call to a member function links() on null

You’ll have to check it at different stages. You are passing that collection to the view, why then is it null when you come to use it? Something else is going on which is not shown here.

Are you sure the links() statement is actually within the component view, and not outside the containing element?

What is the output of @dd($contactnotes) in your view?

$contactnotes is not sent to the view, so it shows as null.

Livewire forces me to use it’s own syntax of $this->contacts->contactnotes(), if I dd() that, I get a list of the contactnotes for that contact. But If I add it the links for pagination, I get the error:
Method Illuminate\Database\Eloquent\Collection::links does not exist

“links” isn’t supposed to be a method of Eloquent is it? This should be the Livewire pagination, not Laravel’s, right?

Links is a method on laravels paginator class. The paginator class is returned when you call paginate on a model, which has to. ($this->foo()->bar is oop syntax, not special to livewire)

All livewire does with the pagination is highjack the view created by the links method that turns the links into livewire, and injects a query string into your component.

If you can’t call paginate on contactnotes(), there’s something wrong with how your relationship is set up. My guess is you are calling ->get() or something there.

Post your relationship method from your contacts model.

Did you import the pagination trait in your livewire component? https://laravel-livewire.com/docs/pagination/

1 Like

If Contractnotes is null, why are you passing it to the view?

I think you have it set up wrong. Try:

public function render()

    {

        return view('livewire.contactshow', [
          'notes' => $this->contacts->contactnotes()->paginate(5)
       ]);

    }

and then use $notes as your foreach iterator and then the links would look like

{{ $notes->links() }}