How to Add Pagination with Union in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Columns Names from Model in Laravel?
- How to Create Model in Laravel using Command?
- Laravel Ajax DELETE Request Example Tutorial
- Laravel Cookies - Get, Set, Delete Cookie Example
- Laravel React JS Image Upload Example
- How to Get Current Year Data in Laravel?
- How to Create and Use Stored Procedure in Laravel?
- Laravel Livewire Delete Confirmation Example
- Laravel Carbon Subtract Months from Date Example
- Laravel 8 Flash Message Tutorial Example
- How to Add Query String Automatically on Laravel Pagination Links?
- Mysql procedure with pagination in laravel?