markrailton's avatar

Having multiple tables with pagination on one page

I have a model called Student and on that have 2 HasMany relationships. In the student.show page I want to show 2 tables, 1 for each of the hasMany relationships.

The model looks like:


class Student extends Model
{
    protected $guarded = [];

    public function sessions()
    {
        return $this->hasMany(Session::class);
    }

    public function sessionsPaginated()
    {
        return $this->sessions()->orderBy('date', 'desc')->paginate(5);
    }

    public function notes()
    {
        return $this->hasMany(StudentNote::class);
    }

    public function notesPaginated()
    {
        return $this->notes()->orderBy('created_at', 'desc')->paginate(5);
    }
}

The issue I've run into is with using the pagination links, im using $student->sessionsPaginated()->links() and $student->notesPaginated()->links() to display the links, but when I click on one of the pagination links it goes to that page on both tables. However, I need it to only do it for the relevant table.

Really hoping someone has an idea about this as I'm completely stuck.

0 likes
3 replies
MichalOravec's avatar
Level 75

You have to set different pageName for each pagination

$this->sessions()->orderBy('date', 'desc')->paginate(5, ['*'], 'sessions');
$this->notes()->orderBy('created_at', 'desc')->paginate(5, ['*'], 'notes']);
1 like
markrailton's avatar

Thanks, that worked perfectly.

For clarity (and anyone else finding this), this is what worked for me:

return $this->notes()->orderBy('created_at', 'desc')->paginate(5, '*', 'notes');

Please or to participate in this conversation.