Courses

Practical Laravel Livewire 2 from Scratch

Live-Search in the Table

Previous: Table with Simple Pagination
avatar

When I try to search a product name from page 1 everything works fine, but if I try to search from another page (like page 2 or 3) I can't see the results instead I click again in page 1.

I'm able to solve that creating a new propriety ($currentPage for example), setting it to 0 by default and changing its value to 1 inside the when() method. Then I called the paginate() method like this:

->paginate(10, ['*'], 'page', $this->currentPage);

It works but I'm wondering if there is a better approach.

My Full component at Gist

[Edit]

Actually I had to change the code. If I set the $currentPage to one insede the when() method, after search for anything I cant change my page number because it's setted as 1. So I remove the code from the when() method. Now I'm changing its value like this:

$this->searchQuery == '' ? $this->currentPage = 0 : $this->currentPage = 1;
👍 2
avatar

Thank you for the valuable comment, Antonio

avatar

Another better approach is set to page 1 when trying to search

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



public function render()
{


    $products = \App\Models\Product::when($this->searchQuery != '', function($query) {
        $query->where('name', 'like', '%'.$this->searchQuery.'%');
    })
    ->paginate(10);

    return view('livewire.product', compact('products'));
}
	
	
avatar

I like that, although if I search for some value from another page than page 1 when I clear the search field I'm back to page one.

avatar

if you have something like live searching functionality then after key change the papge should set to 1.. because search reasult may have small amount of records.

You can use debounce input to not immediately search after keychange . example: wire:model.debounce.500ms

https://laravel-livewire.com/docs/2.x/properties#debouncing-input

public function updatingSearchQuery ()
{
			if ($this->searchQuery) // check if searchQuery is not empty
				$this->resetPage();
}

if you have search button ( not for live searching ) you can use wire:model.defer

https://laravel-livewire.com/docs/2.x/properties#deferred-updating

avatar
You can use Markdown
avatar

I can't find anything about toggling soft deletes in this excelent course. However it is easy. Simply add a checkbox in the form and make it livewire:

<div class="form-check">
	{{ $withTrashed }}
  <input wire:model="withTrashed" class="form-check-input" type="checkbox" value="" id="withTrashed">
  <label class="form-check-label" for="withTrashed">
     Include deleted posts
   </label>
 </div>

Then, in your livewire controller, add

public $withTrashed;

public function mount(){
	 ...
  $this->withTrashed = '';
}
 
 public function render(){
   ...
   ->when($this->withTrashed, function ($query){
                $query->withTrashed();
				})
 }
avatar
You can use Markdown
avatar
You can use Markdown