Search code examples
phplaravellaravel-livewire

Laravel Livewire Pagination Not Displaying Search Results After Index Page


I've seen other posts about this same question, but none of them mirrored my setup, which makes it difficult for me to implement.

I am using Laravel 8.0 and Livewire 1.3

I currently have an 'items' list of 186 items with pagination at 25 per page--this works great. I also have live search and if on the index page, it works great, but if you are on any page after index, for example http://workorders.test/items?page=2 and decide to do a search, it will show the correct number of results, but not display the results to the page(see attached screenshot).

enter image description here

index.php

<?php

namespace App\Http\Livewire\Admin\Items;

use Livewire\Component;
use App\Item;
use Livewire\WithPagination;

class Index extends Component
{
    use withPagination;
    public $item;
    public $item_name;
    public $item_description;
    public $perPage = 25;
    public $sortAsc = true;
    public $search = '';
    public $sortField = 'item_name';

    ...

    public function render()
    {
        $types = collect([
            ['name' => 'Equipment'],
            ['name' => 'Supply'],
        ]);

        $plucked = $types->pluck('name')->all();

        $items = Item::search($this->search)
            ->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
            ->paginate($this->perPage);
        return view('livewire.admin.items.index', compact('items', 'plucked'));
    }
}

item.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Item extends Model
{
    use SoftDeletes;
    protected $fillable = [
        'item_name', 'item_description'
    ];

    public function products()
    {
        return $this->hasMany(Product::class);
    }

    public static function search($query)
    {
        return empty($query) ? static::query()
            : static::where('item_name', 'like', '%'.$query.'%');
    }

}

index.blade (Stripped to show only important pieces)

<div class="flex-1 min-w-0 rounded-md shadow-sm">
   <input wire:model="search" id="search" placeholder="Search Item Name">
</div>
...
@foreach($items as $item)
   ... 
@endforeach
...
{{ $items->links() }}

Solution

  • You're missing something. When you use a filter like that, you need to tell livewire to reset the page.

    In your case, the filter is stored in the $search variable so just add this method to your Livewire Component:

    public function updatingSearch()
    {
        $this->resetPage();
    }