ItSolutionStuff.com

How to Add Pagination with Union in Laravel?

By Hardik Savani β€’ April 16, 2024
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

How to Get Columns Names from Model in Laravel?

Read Now β†’
β˜…

How to Create Model in Laravel using Command?

Read Now β†’
β˜…

Laravel Ajax DELETE Request Example Tutorial

Read Now β†’
β˜…

Laravel Cookies - Get, Set, Delete Cookie Example

Read Now β†’
β˜…

Laravel React JS Image Upload Example

Read Now β†’
β˜…

How to Get Current Year Data in Laravel?

Read Now β†’
β˜…

How to Create and Use Stored Procedure in Laravel?

Read Now β†’
β˜…

Laravel Livewire Delete Confirmation Example

Read Now β†’
β˜…

Laravel Carbon Subtract Months from Date Example

Read Now β†’
β˜…

Laravel 8 Flash Message Tutorial Example

Read Now β†’
β˜…

How to Add Query String Automatically on Laravel Pagination Links?

Read Now β†’
β˜…

Mysql procedure with pagination in laravel?

Read Now β†’