How to Add Pagination with Union in Laravel?

By Hardik Savani April 16, 2024 Category : PHP Laravel

Now, let's see post of laravel pagination with union query. let’s discuss about how to add pagination with union in laravel. you can understand a concept of laravel manual pagination with union query. This article will give you simple example of laravel union pagination.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

If you need to add pagination with union query in laravel then this example will help you with this. in this example, i created two tables "posts" and "items" then i used union query with pagination. so let's see simple example code below:

Example:

You can see below example code here:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

use App\Models\Item;

use Illuminate\Pagination\Paginator;

use Illuminate\Support\Collection;

use Illuminate\Pagination\LengthAwarePaginator;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$page = $request->get('page', 1);

$paginate = 5;

$items = Item::select("id", "title");

$posts = Post::select("id", "title")

->union($items)

->get();

$data = $this->paginate($posts);

$data->withPath('/posts');

return view('posts', compact('data'));

}

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function paginate($items, $perPage = 5, $page = null, $options = [])

{

$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

$items = $items instanceof Collection ? $items : Collection::make($items);

return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);

}

}

I hope it can help you...

Tags :
Shares