Skip to content

Instantly share code, notes, and snippets.

@webdevmatics
Created October 11, 2020 18:34
Show Gist options
  • Save webdevmatics/3890ddf4bb2f3d0f089d036371201a2f to your computer and use it in GitHub Desktop.
Save webdevmatics/3890ddf4bb2f3d0f089d036371201a2f to your computer and use it in GitHub Desktop.
Livewire datatable #livewire
@if ($sortBy !== $field)
<i class=" text-muted fas fa-sort"></i>
@elseif ($sortDirection == 'asc')
<i style="color:rgba(38, 38, 236, 0.774)" class="fas fa-sort-up"></i>
@else
<i style="color:rgba(38, 38, 236, 0.774)" class="fas fa-sort-down"></i>
@endif
<tr wire:loading.class.remove="d-none" class="d-none">
<td colspan="4">
<div class="text-center">
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
</td>
</tr>
<div>
<div class="row mb-4">
<div class="col form-inline">
Per Page: &nbsp;
<select wire:model="perPage" class="form-control">
<option>2</option>
<option>5</option>
<option>10</option>
<option>15</option>
<option>25</option>
</select>
</div>
<div class="col">
<input wire:model.debounce.300ms="search" class="form-control" type="text" placeholder="Search Products...">
</div>
</div>
<table class="table">
<thead>
<tr>
<th wire:click="sortBy('name')" style="cursor: pointer;">
Name
@include('partials._sort-icon',['field'=>'name'])
</th>
<th wire:click="sortBy('description')" style="cursor: pointer;">
Description
@include('partials._sort-icon',['field'=>'description'])
</th>
<th wire:click="sortBy('price')" style="cursor: pointer;">
Price
@include('partials._sort-icon',['field'=>'price'])
</th>
</tr>
</thead>
<tbody>
@foreach ($items as $item)
<tr>
<td>{{$item->name}}</td>
<td>{{$item->description}}</td>
<td>{{$item->price}}</td>
</tr>
@endforeach
</tbody>
</table>
<div>
<p>
Showing {{$items->firstItem()}} to {{$items->lastItem()}} out of {{$items->total()}} items
</p>
<p>
{{$items->links()}}
</p>
</div>
</div>
<?php
namespace App\Http\Livewire;
use App\Product;
use Livewire\Component;
use Livewire\WithPagination;
class Datatable extends Component
{
use WithPagination;
public $sortBy = 'name';
public $sortDirection = 'asc';
public $perPage = 10;
public $search = '';
public function render()
{
$items = Product::query()
->search($this->search)
->orderBy($this->sortBy, $this->sortDirection)
->paginate($this->perPage);
return view('livewire.datatable',[
'items'=> $items
]);
}
public function sortBy($field)
{
if ($this->sortDirection == 'asc') {
$this->sortDirection = 'desc';
} else {
$this->sortDirection = 'asc';
}
return $this->sortBy = $field;
}
public function updatingSearch()
{
$this->resetPage();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment