In this tutorial, you’ll learn to livewire dropdown Sorting and Pagination using Laravel Livewire Package.
suppose i want to sort my product page filter like single page App then i will use livewire
let create Component
php artisan make:livewire ProductComponent
COMPONENT CREATED 🤙
CLASS: app/Http/Livewire/ProductComponent.php
VIEW: resources/views/livewire/product-component.blade.php
it look like this
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ProductComponent extends Component
{
public function render()
{
return view('livewire.product-component');
}
}
now add (use Livewire\WithPagination)
<?php
namespace App\Http\Livewire;
use App\Models\Product;
use Livewire\Component;
use Livewire\WithPagination;
class ProductComponent extends Component
{
use WithPagination;
public $sortBy;
public $perPage;
public function mount()
{
$this->sortBy = "default";
$this->perPage = 6;
}
public function render()
{
if ($this->sortBy == 'latest') {
$products = Product::latest()->paginate($this->perPage);
} else if ($this->sortBy == 'oldest') {
$products = Product::oldest()->paginate($this->perPage);
} else if ($this->sortBy == 'featured') {
$products = Product::where('featured', true)->paginate($this->perPage);
} else if ($this->sortBy == 'low') {
$products = Product::orderBy('price', 'asc')->paginate($this->perPage);
} else if ($this->sortBy == 'heigh') {
$products = Product::orderBy('price', 'desc')->paginate($this->perPage);
} else {
$products = Product::paginate($this->perPage);
}
return view('livewire.product-component', ['products' => $products]);
}
}
In : resources/views/livewire/product-component.blade.php
we can bind model using wire:model so it will link to sortBy
<div class="sort-item ">
<select name="sortBy" class="chosen" wire:model="sortBy">
<option value="default" selected="selected">Default sorting</option>
<option value="latest">Sort by Latest Product</option>
<option value="oldest">Sort by Oldest Product</option>
<option value="heigh">Sort by Featured Product</option>
<option value="low">Sort by price: low to high</option>
<option value="heigh">Sort by price: high to low</option>
</select>
</div>
also we can set perPage bind
<div class="sort-item product">
<select name="perPage" class="use-chosen" wire:model="perPage">
<option value="6" selected="selected">6 per page</option>
<option value="9">9 per page</option>
<option value="12">12 per page</option>
<option value="18">18 per page</option>
<option value="21">21 per page</option>
<option value="24">24 per page</option>
</select>
</div>