nazar1987's avatar

pagination with union in Laravel

i have problem when try pagination tow union table

$page = Input::get('page', 1);
$paginate = 10;
 
$members = DB::table("members")
            ->select("id", "first_name", "last_name", "email", "created_at")
            ->where("site_id", $id);
$users = DB::table("users")
            ->select("id", "first_name", "last_name", "email", "created_at")
            ->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('your_view_name',compact('data'));

this error appear

Class Illuminate\Support\Facades\Paginator does not exist
0 likes
7 replies
thomaskim's avatar

@nazar1987 First, choose between Paginator and LengthAwarePaginator. Think of Paginator as simplePaginate and LengthAwarePaginator as regular paginate.

For Paginator, you can do something as...

// $slice = the sliced array of results. You used the variable $slice for this in your example
// $paginator = the number of results on that page. You used the variable $paginator in your example
$data = new Paginator($slice, $paginator);

I'd suggest reading the docs and taking a look at the source code to understand them better.

jservingo's avatar

Sí se puede

Ya lo probé y funciona bien

$q1 = Model::createByMe();       // some condition
$q2 = Model::createByMyFriend(); // another condition

$q2->union($q1);
$querySql = $q2->toSql();

$query = Model::from(DB::raw("($querySql) as a"))->select('a.*')->addBinding($q2->getBindings());

$paginated_data = $query->paginate();
munazzil's avatar

If you would like to get the user to paginate you can use as like below.

            $user = User::oldest()->paginate(10);

Please or to participate in this conversation.