Laravel Elasticsearch with Pagination Example

By Hardik Savani November 5, 2023 Category : Laravel Elasticsearch

If you haven't install elasticsearch and you don't know how to install elasticsearch in laravel then you have to see first bellow link, in this link you can set up elasticsearch from scratch like install package, use with laravel model etc. :

How to use elasticsearch from scratch in laravel 5?.

After finish step of above link, we can make elasticsearch with pagination view using laravel pagination eloquent. after impletement this example we could find layout like as bellow link.

Preview

Ok, we have to just few changes and we can make pagination in our laravel application. so first open ItemSearchController.php controller and replace index method this way.

app/Http/Controllers/ItemSearchController.php

....

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

if($request->has('search')){


$page = $request->input('page', 1);

$paginate = 3;


$items = Item::searchByQuery(['match' => ['title' => $request->input('search')]], null, null, $paginate, $page);


$offSet = ($page * $paginate) - $paginate;

$itemsForCurrentPage = $items->toArray();

$items = new \Illuminate\Pagination\LengthAwarePaginator($itemsForCurrentPage, $items->totalHits(), $paginate, $page);

$items->setPath('ItemSearch');


}


return view('ItemSearch',compact('items'));

}

....

Ok, at last we have to just render pagination view using laravel pagination eloquent in blade file. so open ItemSearch.blade.php file and change this:

ItemSearch.blade.php

.....

<div class="col-lg-12">

@if(!empty($items))

@foreach($items as $key => $value)

<h3 class="text-danger">{{ $value['title'] }}</h3>

<p>{{ $value['description'] }}</p>

@endforeach

{!! $items->appends(Input::all())->render() !!}

@endif

</div>

....

Try this one......

Shares