Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ralphmorris's avatar

Query two different models and merging with pagination

I have two Models Conversation and DirectEnquiry that I would like to query together and show in the same list of results with pagination.

This is where I am at:

        $conversations = $user->conversations()
                                ->inbox($filters)
                                ->with('job')
                                ->paginate(20);

        $directEnquiries = $user->directEnquiries()->paginate(20);

        $conversations = $conversations->merge($directEnquiries)->sortBy(function($item) {
            
            return $item->updated_at;

        })->reverse();

This works fine until it hits the pagination method at the bottom of the view

{!! $conversations->links() !!}

I am getting the following error message:

ErrorException in Macroable.php line 74:
Method links does not exist.

I've tried playing with unions also but as these are two different models that won't work.

Any ideas?

Thanks!

Ralph

0 likes
4 replies
click's avatar

@jlrdw that is 2 paginations on one page. @ralphmorris wants 1 pagination on one page but from 2 different collections.

I think you have two options

  1. Create two collections, merge them and use https://laravel.com/docs/5.6/pagination#manually-creating-a-paginator. But I think this won't give you the result you want. For example you now pick 20 of collection A and 20 of collection B and sort them on updated_at. Imagine collection A only has dates in 2018 and collection B has only dates in 2017. You will see on every page 20 records of 2018 and 2017.... and I think that is not what you want. You probably want to see all records of 2018 first and on the later pages the records of 2017....
  2. Create indeed a union query, sort the results and paginate that result. If you union multiple queries you must define the same columns. So if you want to union two different tables into one resultset you must return the same fields. See https://laravel.com/docs/5.6/queries#unions for an example that uses union with a sort and https://laravel.com/docs/5.6/queries#unions for the union() method eloquent has available.
1 like
jlrdw's avatar

Is directEnquiries a child table of conversations? Or vice versa. If so you could set up a one-to-many relationship.

1 like
ralphmorris's avatar

Thanks very much for everyones input. Direct Enquiries were a separate table with no relationship to conversations. hence I was trying to Union them somehow. However following from your comments I realised there was no reason why a direct enquiry couldn't be a child of a conversation as a conversation already hasMany messages so I created a hasOne directEnquiry and now only need to query the one table.

Not sure who to mark as best answer but all good advice thank you!

Please or to participate in this conversation.