Laravel pagination

How to create pagination in laravel?

My model

Message

function comments() {

    return $this->hasMany('Comment')
                ->orderBy('created_at', 'desc');
}

      

A comment

function posts(){

    return $this->belongsTo('Post');
}

      

User

function posts(){

    return $this->hasMany('Post');
}


function comments(){

    return $this->hasMany('Comment');
}

      

UserController

$user = User::find(1); //this will give me all the user post and comment details

//i know I can do  $user = User::paginate(30) to get 30 user per page

      

What i want to achieve

I want to create a breakdown of 10 comments per page.

Thanks for your help in advance.

+3


source to share


2 answers


You have two options: you can call paginate()

relationships in the query, or you can manually create the paginator.

Call paginate()

relationships in query (uses relationship function):

$user = User::find(1);
$comments = $user->comments()->paginate(10);

      



Create paginator manually (uses relationship attribute):

$user = User::find(1);
$paginator = Paginator::make($user->comments, $user->comments->count(), 10);

      

Documentation on pagination can be found here .

+3


source


Try it,

$ only10comments = User :: with ('comments') β†’ paginate (10);

If you are using the following previous links in pagination, use simplePaginate.



$ only10comments = User :: with ('comments') β†’ simplePaginate (10);

Hope it helps.

+1


source







All Articles