fetch404's avatar

Collection pagination problem

I'm having a problem with paginating collections.

I made a search function, and it gets all the results fine. But when I try to use the paginator... well, it shows the same stuff on every page. If someone could help, I would appreciate it.

My search function:

    /**
     * Search in the database for certain items
     *
     * @param SearchRequest $request
     * @return mixed
     */
    public function search(SearchRequest $request)
    {
        $searchQuery = ($request->has('query') ? $request->input('query') : Input::old('query'));

        $resultsArray = [];

        // Search in the topics table
        $topics = $this->topic->where('title', 'like', '%' . $searchQuery . '%')->get();
        foreach($topics as $topicResult)
        {
            $resultsArray[] = $topicResult;
        }

        // Search in the users table
        $users = $this->user->where('name', 'like', '%' . $searchQuery . '%')->get();
        foreach($users as $userResult)
        {
            $resultsArray[] = $userResult;
        }

        // Search in the posts table
        $posts = $this->post->where('content', 'like', '%' . $searchQuery . '%')->get();
        foreach($posts as $postResult)
        {
            $resultsArray[] = $postResult;
        }

        // Search for reports
        $reports = $this->report->where('reason', 'like', '%' . $searchQuery . '%')->get();
        foreach($reports as $reportResult)
        {
            $resultsArray[] = $reportResult;
        }

        // Search for conversations
        $conversations = $this->conversation->where('subject', 'like', '%' . $searchQuery . '%')->get();
        foreach($conversations as $conv)
        {
            $resultsArray[] = $conv;
        }

        $resultsCollection = Collection::make($resultsArray);

        $resultsCollection = $resultsCollection->filter(function($item)
        {
            if ($item instanceof User)
            {
                return !$item->isBanned() and $item->isConfirmed();
            }

            if ($item instanceof Topic)
            {
                return $item->canView;
            }

            if ($item instanceof Post)
            {
                return $item->topic->canView;
            }

            if ($item instanceof Report)
            {
                return Entrust::can('viewReports');
            }

            if ($item instanceof Conversation)
            {
                return (
                    Auth::check()
                    &&
                    in_array(Auth::id(), $item->participantsUserIds())
                );
            }
        });

        $resultsCollection = $resultsCollection->sortBy(function($item)
        {
            if ($item instanceof Conversation)
            {
                return 'conversation_' . mb_strtolower($item->subject);
            }

            if ($item instanceof User)
            {
                return 'user_' . mb_strtolower($item->name);
            }

            if ($item instanceof Topic)
            {
                return sprintf('topic_%-12s%s', mb_strtolower($item->title), $item->posts()->count());
            }

            if ($item instanceof Post)
            {
                if (($item->updated_at == null || $item->updated_at->toDateTimeString() <= $item->created_at->toDateTimeString()))
                {
                    return sprintf('post_%s%-12s', mb_strtolower($item->content), $item->created_at);
                }

                return sprintf('post_%s%-12s', mb_strtolower($item->content), $item->updated_at);
            }

            if ($item instanceof Report)
            {
                return sprintf('report_%-12s', mb_strtolower($item->reason));
            }

        });

        $perPage = 10; // Item per page (change if needed)
        $currentPage = Input::get('page') != null ? Input::get('page') : 1;

        $pagedData = $resultsCollection->slice($currentPage * $perPage, $perPage)->all();

        $results = new Paginator($pagedData, $perPage);

    $results->setPath('search')->appends('query', $searchQuery);

        return view('core.search.search', compact('results', 'resultsCollection', 'searchQuery'));
    }

The search view:

@extends('core.partials.layouts.master')
@section('title', 'Search')
{{-- Content here --}}
@section('content')
    <h1>Search</h1>
    <hr>
    <div class="well">
        @if (!isset($results))
            <p>Please enter a search query.</p>
        @else
            @if (empty($results))
                <p>No results were found.</p>
            @else
                <h1>Your search returned {{{ $resultsCollection->count() }}} {{{ Pluralizer::plural('result', $resultsCollection->count()) }}}</h1>
                <ul class="list-group">
                @foreach($results as $item)
                  <li class="list-group-item">
                      @if ($item instanceof App\User)
                        <i class="fa fa-user fa-fw"></i>
                        {!! link_to($item->profileURL, str_limit(strip_tags($item->name), 15)) !!}
                        <span class="pull-right">
                            <span class="text-muted">
                                Joined {{{ $item->created_at->diffForHumans() }}}
                            </span>
                        </span>
                      @elseif ($item instanceof App\Post)
                        <i class="fa fa-comment fa-fw"></i>
                        {!! link_to($item->Route, str_limit(strip_tags($item->content), 50)) !!}
                        <span class="pull-right">
                            <span class="text-muted">
                                {{{ $item->created_at->diffForHumans() }}}
                            </span>
                        </span>
                      @elseif ($item instanceof App\Topic)
                        <i class="fa fa-comments-o fa-fw"></i>
                        {!! link_to($item->Route, str_limit(strip_tags($item->title), 50)) !!}
                        <span class="pull-right">
                            <span class="text-muted">
                                {{{ $item->created_at->diffForHumans() }}}
                            </span>
                        </span>
                      @elseif ($item instanceof App\Report)
                        <i class="fa fa-exclamation-circle fa-fw"></i>
                        {!! link_to_route('reports.view', "Report by " . $item->owner->name, [$item]) !!}
                        <span class="pull-right">
                            @unless(!$item->isClosed())
                            <i class="fa fa-lock fa-fw" data-type="tooltip" data-original-title="Closed"></i>
                            @endunless
                            <span class="text-muted">
                                Reported {{{ $item->created_at->diffForHumans() }}}
                            </span>
                        </span>
                      @elseif ($item instanceof Cmgmyr\Messenger\Models\Thread)
                        <i class="fa fa-envelope fa-fw"></i>
                        {!! link_to_route('conversations.show', str_limit($item->subject, 25), [$item->id]) !!}
                        <span class="pull-right">
                            <span class="text-muted">
                                {{{ $item->created_at->diffForHumans() }}}
                            </span>
                        </span>
                      @endif
                  </li>
                @endforeach
                </ul>
                {!! $results->render() !!}
            @endif
        @endif
    </div>
@endsection

I really don't know what's going on. Help, please.

0 likes
2 replies
fetch404's avatar

Okay, never mind, it sort of works, but the pagination controls are not showing for the first page.

beznez's avatar

What happens if you call paginate with the method instead of the object, like this:

$results = $resultsCollection->paginate($perPage);

Please or to participate in this conversation.