Today now in this blog I will show you How to add pagination with union in Laravel 4 and Laravel 5. If you are using union and also you want to use pagination, but you can’t do that. Then here i also fetch that problem and if you use union with pagination. Then you have to create a pagination manually by using Paginator Class. And if you are using Laravel 4 then you can use Paginator Class library and when you use Laravel 5 then you have to give help of \Illuminate\Pagination\LengthAwarePaginator Class function.
Now you have to many times need give a manually pagination as like as if we are using having, union etc. So now i am giving you a example of Laravel 4 and Laravel 5 both we 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')); } }
Read Also : Laravel QR Code Generator Example
Thanks for read this, I hope it will you. You can also follow us on Facebook.