The Laravel Union Paginator package by Austin White combines data from multiple Eloquent models into a single unified query using SQL unions. With this package, you can get "consistent pagination and customization across diverse data sources."
The UnionPaginator
class is configured with models that extend the base Eloquent Model
class. You have control over transforming each model's records and calling paginate()
on the UnionPaginator
instance after configuring it:
use AustinW\UnionPaginator\UnionPaginator;
// Define the models
$paginator = UnionPaginator::for([User::class, Post::class]);
// Apply transformations
$paginator->transform(User::class, fn($record) => [
'id' => $record->id,
'name' => $record->name,
])->transform(Post::class, fn($record) => [
'title' => $record->title,
'created_at' => $record->created_at,
]);
// Paginate the results
$paginatedResults = $paginator->paginate(10);
// Iterate through paginated items
foreach ($paginatedResults->items() as $item) {
// Process the paginated item
}
The Union Paginator package works with both Laravel v10 and Laravel v11. To get started with this package, check it out on GitHub at austinw/laravel-union-paginator.
The post Paginate Multiple Eloquent Models with the Union Paginator Package appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.