Laravel 8- Elasticsearch with pagination

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show how to show data with pagination in Elasticsearch in laravel 8. If you have no idea about how to install Elasticsearch and if you don’t know how to install the Elasticsearch in laravel then you can see first my past post based on Elasticsearch in bellow link, so in this link we can set up Elasticsearch from the scratch like install package, and use with laravel model etc. : How to use elasticsearch from scratch in laravel?

So after finish step of above link, you can make Elasticsearch with pagination view by using laravel pagination eloquent.

Ok, now we have to just need few changes and we can make the pagination in our laravel application also. So at first open ItemSearchController.php controller and need to 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, now at last we need to just render the pagination view by using laravel pagination an eloquent in blade file. So need open ItemSearch.blade.php file and then 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>
....

Read Also : How to Use Group by year month using Laravel Query Builder ?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →