Pagination problem in search option in Laravel

Published 1 week ago by AbdulBazith

I am having a textbox which searches the data and displays in tabular format. The search box works when I type any text it in that is it works in “Onkeyup” event written in Ajax .

When the view page loads all the data are displayed to the user. I have given pagination for the view.

When the user type any name in the search box it goes to the function in controller by Ajax call and searches for the result and then displays only the matched values to the user. But the pagination remains same as for the first view. If I change the page number then the page is refreshed. How to solve this?

This is my controller Sales_detailsController


public function index()
    {
        $sales = Sales_details::orderBy('created_at','desc')->paginate(5);

        return view('Sales_details.view')->withsales($sales);
    }


This is my view. Blade



@extends('main')

@section('title','| All data Sales')

@section('content')

<div class="row">
        <div class="col-md-10">


        </div>
     <div class="col-md-2">
            <a href="{{ route('Sales_details.create') }}" class="btn btn-lg btn-block btn-primary btn-h1-spacing"> Sales Entry</a>
     </div>
<hr>
</div><!-- end of row-->

<div class="row">
<div class="col-md-12">

        <caption><h2 align="center">SALES ENTRY PREVIEW</h2></caption>


{{ Form::text('search_a',null ,array('class'=>'form-control','id'=>'search_a','name'=>'search_a')) }}<br>

    <table  id="sales_details" class="table table-bordered">
      
      <thead>

              <th >Sales Id</th>
              <th>Date</th>
              <th>Time</th>
              <th>Customer Id</th>
              <th>Customer Type</th>
              <th>Customer Name</th>
              <th>Customer Area</th>
              <th>Customer Booth</th>
              <th>Rate/Litre</th>
              <th>No of Litres</th>
              <th>Total</th>
              <th>Note</th>
              <th>Action</th>

      </thead>

      <tbody>
            @foreach($sales as $sal)
                <tr>
                    {{-- <th>{{ $ven->id }}</th> --}}
                    <td>{{ $sal->sales_id }}</td>
                    <td>{{ $sal->date }}</td>
                    <td>{{ $sal->time }}</td>
                    <td>{{ $sal->customer_id }}</td>
                    <td>{{ $sal->customer_type }}</td>
                    <td>{{ $sal->customer_name }}</td>
                    <td>{{ $sal->customer_area }}</td>
                    <td>{{ $sal->customer_booth }}</td>
                    <td>{{ $sal->rate_per_litre }}</td>
                    <td>{{ $sal->no_of_litre }}</td>
                    <td>{{ $sal->total }}</td>
                    <td>{{ $sal->note }}</td>

    <td>
        <a href="{{ route('Sales_details.show',$sal->id) }}" class="btn btn-success btn-sm" style="width: 100%;">View</a>

    </td>  
           
                </tr>
            @endforeach
      </tbody>
      </table>

            <div class="text-center">             

                {!! $sales->Links(); !!} 
            </div>

</div>
</div>
<script type="text/javascript"> 

$('#search_a').on('keyup',function(){

$value=$(this).val();

$.ajax({

type : 'get',

url : '{{URL::to('search_name')}}',

data:{'search_name':$value

},

success:function(data){

 $('tbody').html(data);

}

});


})

    </script>

@endsection


This is my java script


<script type="text/javascript"> 

$('#search_a').on('keyup',function(){

$value=$(this).val();

$.ajax({

type : 'get',

url : '{{URL::to('search')}}',

data:{'search_name':$value

},

success:function(data){

 $('tbody').html(data);

}

});


})

    </script>


This is my controller for search the function search()


public function search( Request $request )

    {

                    $output="";

                    $sales=Sales_details::
                      where('sales_id','LIKE','%'.$request->search_name.'%')
                      ->orwhere('date','LIKE','%'.$request->search_name.'%')
                      ->orwhere('time','LIKE','%'.$request->search_name.'%')
                      ->orwhere('customer_id','LIKE','%'.$request->search_name.'%')
                    ->orwhere('customer_name','LIKE','%'.$request->search_name.'%')
                    ->orwhere('customer_type','LIKE','%'.$request->search_name.'%')
                    ->orWhere('customer_area','LIKE','%'.$request->search_name.'%')
                    ->orWhere('customer_booth','LIKE','%'.$request->search_name.'%')
                    ->orWhere('no_of_litre','LIKE','%'.$request->search_name.'%')
                    ->orWhere('rate_per_litre','LIKE','%'.$request->search_name.'%')
                    ->orWhere('total','LIKE','%'.$request->search_name.'%')
                    ->orWhere('note','LIKE','%'.$request->search_name.'%')
                    ->paginate(10);

                     if($sales)

                    {

                    foreach ($sales as $key => $sale)
                    {

                    $output.='<tr>'.

                    '<td>'.$sale->sales_id.'</td>'.

                    '<td>'.$sale->date.'</td>'.

                    '<td>'.$sale->time.'</td>'.

                    '<td>'.$sale->customer_id.'</td>'.

                    '<td>'.$sale->customer_type.'</td>'.

                    '<td>'.$sale->customer_name.'</td>'.

                    '<td>'.$sale->customer_area.'</td>'.

                    '<td>'.$sale->customer_booth.'</td>'.

                    '<td>'.$sale->no_of_litre.'</td>'.

                    '<td>'.$sale->rate_per_litre.'</td>'.

                    '<td>'.$sale->total.'</td>'.

                    '<td>'.$sale->note.'</td>'.

                    '<td>'

                    ."<a href='' class='btn btn-success btn-sm' style='width: 100%;'>View</a>".

                    '</td>'.

                    '</tr>';

                    }

                    return Response($output);
                    }

    }


When page load the pagination is ok. but after search the pagination is not changing. the old pagination is displayed and if i change the page after search once again it reloads the page so that my searched keyword disappears.

How to solve this??

pardeepkumar

If you want to apply filters to the next page you should add them to your paginator like this:

$product = Product::where('naam', 'LIKE', '%' . $q . '%')
        ->orWhere('beschrijving', 'LIKE', '%' . $q . '%')
        ->paginate(6);
$product->appends(['search' => $q]);
And change your route from post to get:

Route::get('search', '[email protected]');

AbdulBazith

@pardeepkumar it not working.. after filter also the old pagination is displayed. before filter my records are more then 50 so i displayed just 5 per page that is paginate(5) so it took 10 pages.

But after filter my record will be just 6 or 7. i have given paginate(10). so here it must be in only one page with 7 records.

but it shows 10 pages i think after filter the pagination not working

BezhanSalleh

I would go with query scope

https://laravel.com/docs/5.6/eloquent#local-scopes

but you can checkout the following links

https://www.cloudways.com/blog/live-search-laravel-ajax/

https://shareurcodes.com/blog/ajax%20live%20search%20table%20generation%20in%20laravel

QueryScope Example: or give this a try... on mobile haven't tested but the logic is sound so you might not run into any problem... it readable which is supposed to be... any problems let me know.. cheers...

//ProductsController

public function index(Request $request)
{
    Product::latest()->paginate(10);
    if($request->ajax())
    {
        $products = Product::search($request->keyword)
                        ->latest()
                        ->paginate(10)
                        ->appends(['keyword'=>$request->keyword]);
        return view('products._searchResult',compact('products'));
    }

    return view('products.index', compact('products'));

}

//Route
Route::resource('products', 'ProductsController');
//Product Model

public function scopeSearch($query,$keyword)
{
    $query->where('name','like',"%$keyword%");// add as many column searchs as you wants 
                                                //->orWhere('category','like',"%$keyword%")

}

//products._searchResult

    @if($products->count())
        @foreach($products as $product)
            <li>{{ $product->name }}</li>
            <li>{{ $product->category->name }}</li>
            <li>{{ $product->package->type }}</li>
        @endforeach
    @endif
{!! $product->links() !!}
    
//products.index

<div class="form-group">
    <input type="text" name="keyword" class="form-control" id="keyword" />
</div>

<div id="list">
    @include('products._searchResult')
</div>


<script>
    $("#keyword").on('keyup',function(){
        var search = $(this).val();
        $.ajax({
            url: '{{ route('products.index') }}',
            type: 'get',
            data: {keyword: 'search'},
        })
        .done(function(data) {
            $("#list").empty().html(data);
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
        
    })
</script>

AbdulBazith

@BezhanSalleh thank you, wait i will try and reply

Please sign in or create an account to participate in this conversation.