FutureWeb's avatar

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();
0 likes
7 replies
SilenceBringer's avatar

@futureweb if you need names only

$users = User::where('role_id','=',1)->select('name')->distinct()->paginate(20);
Snapey's avatar
Snapey
Best Answer
Level 122

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();
1 like
FutureWeb's avatar

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

webrobert's avatar

@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();

1 like
webrobert's avatar

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();

Snapey's avatar

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.