You can do your own query and then manually create the pagination, see this thread: https://laracasts.com/discuss/channels/eloquent/paginate-eloquent-collection
Subquery with Eloquent and pagination
Hello,
I have a MySQL database table with a large number of rows. I noticed that the ORDER BY clause is heavily slowing down the query. A nice solution for this is to wrap the query inside a subquery to make it run much faster. In plain MySQL, my query will be:
SELECT * FROM
(SELECT products.id, categories.name FROM products
INNER JOIN categories ON products.category_id=categories.id
) as t ORDER BY id desc
Right now I'm having trouble to translate that query to Eloquent. Since I also want Laravel to paginate the results, it should be something like this:
Product::select('products.id', 'categories.name')
->join('categories', 'products.category_id', '=', 'categories.id')
->orderBy('products.id', 'desc');
->paginate(30);
Obviously, this doesn't do the trick as I'm not sure how to produce a subquery with Eloquent and use pagination on that.
Any help is highly appreciated. Thanks!
In that case you can do it like so
// This returns a Query builder object
$subQuery = Products::select('products.id', 'categories.name')
->join('categories', 'categories.id', '=', 'products.category_id');
$data = DB::table(DB::raw("({$subQuery->toSql()}) as t"))
->mergeBindings($subQuery->getQuery())
->orderBy('id', 'desc')
->get();
Note: I didn't tested this, but I think it should work ;)
Please or to participate in this conversation.