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;

$feed = UnionPaginator::forModels([Post::class, Comment::class])
    ->latest()
    ->paginate(20);

foreach ($feed as $item) {
    // $item is a Post or a Comment model, newest first.
}

UnionPaginator::forModels([Post::class, Comment::class])
    ->where('created_at', '>=', now()->subWeek())
    ->whereIn('type', [Post::class, Comment::class])
    ->orderByDesc('created_at')
    ->paginate();

$paginator->when($onlyPosts, fn ($paginator) => $paginator->where('type', Post::class));

$paginator->applyScope(Post::class, fn ($query) => $query->where('published', true))
          ->applyScope(Comment::class, fn ($query) => $query->whereHas('post'));

$paginator->paginate(15);          // LengthAwarePaginator, with a total
$paginator->simplePaginate(15);    // next/previous only, skips the COUNT over the union
$paginator->cursorPaginate(15);    // cursor pagination for large or infinite feeds

$paginator->fetchModelsUsing(Post::class, fn (array $ids) => Post::with('author')->findMany($ids));

$paginator->preventModelRetrieval()->paginate();

$paginator->transformResultsFor(Post::class, fn (Post $post) => [
    'title' => $post->title,
    'date' => $post->created_at->toDateString(),
]);

$paginator
    ->setSelectedColumns(Post::class, ['posts.id as id', 'posts.published_at as created_at', 'posts.title as title'])
    ->setSelectedColumns(Comment::class, ['comments.id as id', 'comments.created_at', 'comments.body as title']);