motinska94's avatar

Get first, paginate later

Is there a way to get all the data first and paginate after? I need all the categories' names and ids to show in a select box, but in the same page I have a table that contains the same categories and I don't want that table to be too crowded -- therefore, paginate.

So in a nutshell : select option should have all the data but table needs to be paginated. I don't want to use 2 different queries to get the same data because well, it's the same data. Only one of them needs to be paginated.

is there a way to do this without building the pagination myself from scratch?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Just execute two queries, it'll very likely be more performant than whatever else you're considering:

$selectableCategories = Category::pluck('name', 'id');

$categories = Category::paginate(20);

It is not the same data because (i) the selectable categories only need an id and name (or title or whatever) and (ii) the record set is different.

1 like
motinska94's avatar

@tykus I was trying something like this below, but you're right 😄 there's way less queries when I query the db twice.

$cats_all = Category::orderBy('updated_at', 'desc');
$categories = $cats_all->with('parent:id,name');
$paginated = $categories->paginate($this->paginate_count);
$categories = $categories->get(['id','name','parent_id','updated_at']);

Please or to participate in this conversation.