Pagination and Pluck not plucking entire collection
is there a way to pluck values before pagination? I am only getting the names from the first 20
$users = User::where('role_id','=',1)->paginate(20);
$userNames = $user->pluck('name')->unique();
@futureweb if you need names only
$users = User::where('role_id','=',1)->select('name')->distinct()->paginate(20);
if you want both sets of data, you will need to run two queries
$users = User::where('role_id','=',1)->paginate(20);
$userNames = User::where('role_id','=',1)->pluck('name')->unique();
Ah I was hoping to avoid 2 queries in reality its a pretty big query with lots of joins and I pluck several unique arrays from the collection
@futureweb, of course, you can avoid 2 queries...
$users_paginate = User::where('role_id','=',1)->paginate(20);
$the_actual_users = collect($users_paginate)['data'];
$userNames = collect($the_actual_users)->pluck('name')->unique();
// or shorter
$userNames = collect($users_paginate->items())->pluck('name')->unique();
@webrobert that still only gets the names out of the first 20 results.
ahh, my bad. I misread. Too early for me to read properly apparently.
@futureweb, maybe use clone for the pretty big query with lots of joins and I pluck several unique arrays
$pretty_big_query_with_lots = User::where('role_id','=',1); // NO get()
(clone $pretty_big_query_with_lots)->paginate(12);
$pretty_big_query_with_lots->pluck('name')->unique();
You can avoid writing the query twice, but you can't avoid performing the query twice because pagination will apply a limit.
Please or to participate in this conversation.