In previous posts we saw about pagination and search functionality individually. Here we ‘ll combine search functionality with paginated data results.
Its quite common to inculude search option and pagination functionality for displaying any type of large data. So instead of using some table table extenders which fetch all the records at a time its better to use built in paginators which only gets the required number of records each time.
Here in this elegant framework, Laravel, its quite easy to implement these functionalities with very few lines of code.
First we ‘ll show a chunks of dummy data with about 1000 rows and limiting to only 25 rows per page. This dummy data is collected from Mockaroo.com.
Route::get ( ‘/’, function () { $dummyDetails = User::paginate(25); return view ( ‘welcome’ )->withUsers($dummyDetails); } );
Route::get ( ‘/’, function () { $dummyDetails = User::paginate(25); return view ( ‘welcome’ )->withUsers($dummyDetails); |
for reference, you can find the dummy details sql file here
Pagination View :
Now in the view file welcome.blade.php, we show this data limiting to only 25 results per page.
@if(isset($users))
Sample User details
@foreach($users as $dummy) @endforeach
Name | |
---|---|
{{$dummy->name}} | {{$dummy->email}} |
{!! $users->render() !!}@endif
Sample User details@foreach($users as $dummy) {!! $users->render() !!}@endif
Search Form :Now we ‘ll use the form for search field which we created in previous post on Search functionality. {{ csrf_field() }} Pagination and Search logic :The logic for a handling search is, Route::any ( ‘/search’, function () { $q = Input::get ( ‘q’ ); if($q != “”){ $user = User::where ( ‘name’, ‘LIKE’, ‘%’ . $q . ‘%’ )->orWhere ( ’email’, ‘LIKE’, ‘%’ . $q . ‘%’ )->paginate (5)->setPath ( ” ); $pagination = $user->appends ( array ( ‘q’ => Input::get ( ‘q’ ) ) ); if (count ( $user ) > 0) return view ( ‘welcome’ )->withDetails ( $user )->withQuery ( $q ); } return view ( ‘welcome’ )->withMessage ( ‘No Details found. Try to search again !’ ); } );
Here we used HTTP method any() Here while showing search results we limited data to only 5 results per page. That’s it folks we ‘ve successfully implemented search functionality with paginatated data. Make sure you ‘ve gone through previous posts on search and pagination. |