PHP code example of austinw / laravel-union-paginator
1. Go to this page and download the library: Download austinw/laravel-union-paginator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
austinw / laravel-union-paginator example snippets
use AustinW\UnionPaginator\UnionPaginator;
$paginator = UnionPaginator::forModels([User::class, Post::class]);
use AustinW\UnionPaginator\UnionPaginator;
use App\Models\Post;
use App\Models\Comment;
// Create a new UnionPaginator instance for the specified models
$paginator = new UnionPaginator([Post::class, Comment::class]);
// Register a custom retrieval callback for the Post model
$paginator->fetchModelsUsing(Post::class, function (array $ids) {
// Custom logic to retrieve Post models
return Post::with('author')->findMany($ids);
});
// Register a custom retrieval callback for the Comment model
$paginator->fetchModelsUsing(Comment::class, function (array $ids) {
// Custom logic to retrieve Comment models
return Comment::with('post')->findMany($ids);
});
// Use the paginator as usual
$paginatedResults = $paginator->paginate();
$paginator->setSelectedColumns(User::class, ['id', 'email', DB::raw("'User' as type")]);
use AustinW\UnionPaginator\UnionPaginator;
$paginator = UnionPaginator::forModels([User::class, Post::class])
->applyScope(User::class, fn($query) => $query->where('active', true))
->transformResultsFor(User::class, fn($user) => ['id' => $user->id, 'name' => strtoupper($user->name)])
->transformResultsFor(Post::class, fn($post) => ['title' => $post->title, 'date' => $post->created_at->toDateString()])
->paginate(10);
foreach ($paginator->items() as $item) {
// Each $item could be a transformed array or a raw record, depending on your configuration.
}