murilo's avatar
Level 10

Laravel Pagination with Eloquent does not Work

Hello , I'm trying to paginate with eloquent but I am no been success .

If I paginate like this , It will works -

$messages =  Messages::orderBy('created_at', 'desc')->paginate(10);

But if I try to get all the messages from a user and paginate it , like this -

$messages = $this->user->Messages->paginate(10);

It will not paginate , some one know a better way to do it ? Thanks

0 likes
7 replies
tomopongrac's avatar

Try with query builder

$messages =  DB::table('messages')->orderBy('created_date', 'desc')->paginate(10);
1 like
murilo's avatar
Level 10

Hello Tomi , Thanks . But I wold like to paginate all the messages from a USER . like this I will paginate ALL .

murilo's avatar
Level 10

I dont know if some one here can understand me . I can do it making 2 searches -

  • Fist I collect all IDs Messages , from that user .
  • After I make a new search with whereIn , like this -

Here I get all messages from a User

$messages = $this->user->Messages;

Collect all IDs

$display_items_id = array();
foreach ( $messages as $message){

       array_push($display_items_id , message->id );

}

Make a new search , now with those IDS that I found , AND finaly paginate it whith whereIn .

$get_all_messages_with_pagination = Message::whereIn('id' , $display_items_id )->paginate(20) ;

Some one know A betther way to do it ? I dont know if making 2 searches like this wold be a good approach .

Snapey's avatar

I don't think you can paginate this way as at the top level there is only one item (the user)

$messages = Messages::where('user_id',$this->user->id)->paginate(10);
1 like
murilo's avatar
Level 10

In this situation , yes . I could do it . But in other situation , that some users can see a content , and others can not . I will be not able to put on the table , the Ids of all users that can see the content . So I will have to do on that way .

pmall's avatar
pmall
Best Answer
Level 56

You have to do this $messages = $this->user->Messages()->paginate(10);.

Note the parentheses. $this->user->Messages() returns the relationship instance, which behave like a query builder, so you can select messages with paginate. $this->user->Messages is a collection of messages so it can't work.

1 like

Please or to participate in this conversation.