How to add pagination with union in Laravel 4 and Laravel 5 ?
You are using union and you want to give pagination, but you can't give. i also fetch that problem if you use union with pagination. you have to create pagination manually using Paginator Class. if you are using Laravel 4 then you can use Paginator Class library and if you use Laravel 5 then you have to give help of \Illuminate\Pagination\LengthAwarePaginator Class function. you have to many times need give a manually pagination like if you are using having, union etc. now i am giving you example of Laravel 4 and Laravel 5 both you can do this way.
Laravel 5
namespace App\Http\Controllers;
use Input;
use Request;
use View;
class AdminController extends Controller
{
public function index()
{
$page = Input::get('page', 1);
$paginate = 10;
$members = DB::table("members")
->select("id", "firstname", "lastname", "email")
->where("site_id", $id);
$data = DB::table("users")
->select("id", "firstname", "lastname", "email")
->where("site_id", $id)
->union($members)
->get();
$offSet = ($page * $paginate) - $paginate;
$itemsForCurrentPage = array_slice($data, $offSet, $paginate, true);
$data = new \Illuminate\Pagination\LengthAwarePaginator($itemsForCurrentPage, count($data), $paginate, $page);
return View::make('index',compact('data'));
}
}
Laravel 4
namespace App\Http\Controllers;
use Input;
use Request;
use View;
class AdminController extends Controller
{
public function index()
{
$page = Input::get('page', 1);
$paginate = 10;
$members = DB::table("members")
->select("id", "firstname", "lastname", "email")
->where("site_id", $id);
$users = DB::table("users")
->select("id", "firstname", "lastname", "email")
->where("site_id", $id)
->union($members)
->get();
$slice = array_slice($users, $paginate * ($page - 1), $paginate);
$data = Paginator::make($slice, count($users), $paginate);
return View::make('index',compact('data'));
}
}
you can use this example and you can create pagination, let's you have to try......

My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.