oroalej's avatar

Union with pagination - Laravel 5.6

Hi Guys,

How can I add pagination on a union. I got an error Cardinality Violationwhen using union with ->paginate().

0 likes
11 replies
oroalej's avatar

@biishmar Everything is working fine when I didn't use ->paginate(), but when I do, the error appear. It seems like paginate is not working with union. Is there any work around?

biishmar's avatar

@oroalej would you please show that code? paginate only works for query builder, i think u calling paginate from collection.

Agelios's avatar

@biishmar Its because your queries have different selects. Try use ->select() same fields in both queries and run paginate. This should help

oroalej's avatar

@Agelios I tried adding select to both queries, but it only works when I select 1 column. When I select 2 or more columns, the error showed up again.

@biishmar Like I said, it is working fine if I remove the ->union() code.

Sample code:

$first = Model::SomeConditions;

$second = Model::SomeConditions
                    ->union($first) <<<--- If i remove this, everything is working fine.
                    ->paginate(5);
                    

$first = I'm trying to get only the featured professional where featured_date >= today.

$second = I'm trying to get the latest professional and combining the result with $first.

Agelios's avatar

@oroalej Need full code.

 $first = DB::table('sometable')->select('firstcolumn', 'secondcolumn')->where('somethink', $somethink);
 $second = DB::table('other_table')->select('same_column_as_first, ..')->where(cond)->union($first)->paginate();

its work fine

oroalej's avatar

@Agelios

Here is the code

  $featuredProfessionals = Professional::select('name', 'id')
                          ->WhereNotNull('matterport_url')
                          ->where('name', 'LIKE', "%{$search}%")
                          ->where('featured_ends_at', '>=', now());

  $professionals = Professional::select('name', 'id')
                        ->WhereNotNull('matterport_url')
                        ->where('name', 'LIKE', "%{$search}%")
                        ->union($featuredProfessionals)
                        ->latest()
                        ->paginate(5);
oroalej's avatar

Hi guys,

I was able to make it in one query. But I still want to know how to make it work in case I encounter this problem in the future.

Thank you for your time @biishmar and @Agelios

Please or to participate in this conversation.