How to paginate search results in laravel?
Author
Author

Robert Nicjoo [68]

I love Laravel & WordPress, interested to pass little knowledge that I have to others.

Qr-Code

Scan to visit on mobile

TJD STUDIO is Hiring

Photographer & Videographer

Apply now Jabodetabek

How to paginate search results in laravel?

There is 2 ways to paginating your search results in laravel.

  1. From blade file
  2. From controller file

 

1. From blade file

in your view where you display pagination...

{{ $results->appends(Request::except('page'))->links() }}

appends keeps the query string value except "page".

Note: don't forget to change your route from post to get.

 

2. From your controller file

public function search(Request $request) {

  $search = request('search');

  $posts = Post::where('title', 'like', "%{$search}%")
         ->orWhere('description', 'like', "%{$search}%")
         ->where('publish', '=', 1)
         ->paginate(10);
  $posts->appends(['search' => $search]);

  if(count($posts) > 0) {
    return view('front.search.index', compact('posts', 'search'));
  } else {
    return view ('front.search.index', compact('posts','search'));
  }

}

we have included append to our controller in order to get results in pages while they passed to our url

$posts->appends(['search' => $search]);

 

Simple isn't it?

How do you like this article?

Back to top