webfuelcode's avatar

Search results pagination works not

What is wrong here that the pagination does not work.

<form action="{{ route('search') }}" method="GET" role="search">
                            <div class="search">
                                <input type="text" class="form-control searchTerm" name="q" placeholder="What are you looking for?">
                                <button type="submit" class="searchButton">
                                    <i class="fa fa-search"></i>
                                </button>
                            </div>
                        </form>

Controller:

public function search(Request $request)
    {
        $this->validate($request, [
            'q' => 'required',
        ]);
        $posts = Post::where('title', 'like', '%' . $request->q . '%')->orWhere('description', 'like', '%' . $request->q . '%')->paginate(4);
    
        return view('pages.search', compact('posts'));
    }

Route:

Route::get('search', 'WelcomeController@search')->name('search');
0 likes
6 replies
aurawindsurfing's avatar

You need to display the paginated results properly, have a look here:

https://laravel.com/docs/master/pagination#displaying-pagination-results

<div class="container">
    @foreach ($users as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $users->links() }}

you are not showing the posts anywhere in your code in blade:

<form action="{{ route('search') }}" method="GET" role="search">
                            <div class="search">
                                <input type="text" class="form-control searchTerm" name="q" placeholder="What are you looking for?">
                                <button type="submit" class="searchButton">
                                    <i class="fa fa-search"></i>
                                </button>
                            </div>
                        </form>

<div class="container">
    @foreach ($posts as $post)
        {{ $post->title }}
    @endforeach
</div>

{{ $posts->links() }}

webfuelcode's avatar

The view is:

@forelse ($posts as $post)
            <div class="card my-2">
                <div class="card-body">
                    <h5>
                        <a href="{{ route('post.show', $post->slug) }}">{{ $post->title }}</a>
                    </h5>
                    {!! Str::words($post->description, 25, '...') !!}
                </div>
            </div>
        @empty
            ..No result found..
        @endforelse

        {{ $posts->links() }}
newbie360's avatar

what about use ->paginate(1);

because the records in $posts not more than 4?

ankush981's avatar

use this method pagination work with search also

{{ $posts->appends(request()->except('page'))->links() }}

Please or to participate in this conversation.