Pagination With Appends() in Laravel
Let’s think about how we build out the index page of an application that lists places. We’ll keep it really simple. There will be one router resource called places and will allow it to serve the traditional crud routes. After a short time, the number of places that our application tracks will be too long to display in one page. And will want to give the user a way to search that list as well.
I think a reasonable place to start here would be to add a search box to the index page, and then make a get request back to the index route filtered down to the results that match. Here’s an example of that controller code:
class PlaceController extends Controller
{
/*
* Display a listing of the resource.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function index(Request $request): View
{
$places = Place::where(
"title",
"like",
"%" . $request->query("search") . "%"
)->paginate(10);
return view("places.index", [
"places" => $places,
]);
}
}
We probably also want to use Laravel’s built-in pagination tool. But there’s a problem, if we click on any of those pagination links. After we make a search, the search parameter will be removed and we’ll see a list of all the places.
To avoid that, we can update the controller code to use the appends method. This will check to see if our request started with a search parameter and pass it forward when creating the links for pagination.
public function index(Request $request): View
{
$places = Place::where(
"title",
"like",
"%" . $request->query("search") . "%"
)
->paginate(10)
->appends(["search" => $request->query("search")]);
return view("places.index", [
"places" => $places,
]);
}