1
votes

I try to add a specific element in a paginated list with laravel.

In the URL, there is a parameter to see a specific user in my list (the parameter is the user's id). I get the parameter like this:

$openUserId = \Input::get('user', null);

After that, I've got a list of users with pagination like this:

$users = User::filter($filter)
        ->with('company')
        ->isNot(Role::ADMIN)
        ->whereNotIn('id', [auth()->user()->id])
        ->where('status', 'active')
        ->paginate(10)
        ->appends($request->except('page'));

I'd like to create my list of users with the user in the url added in the 10 first results, because sometimes the user required isn't in the 10 first users.

I can't create a collection or something like that because I need to keep functions from the pagination (like nextPageUrl() or hasMorePages()).

1

1 Answers

1
votes

You need to get these users with two queries, merge the collections and create LengthAwarePaginator paginator manually using the merged collection:

$users = User::with('company')->take(1)->get();

$usersToMerge = User::filter($filter)
    ->with('company')
    ->isNot(Role::ADMIN)
    ->where('id', '!=', auth()-id())
    ->where('status', 'active')
    ->take(9)
    ->get();

$users->merge($usersToMerge);