Jun 4, 2024
0
Level 1
Validating GET Parameters - Sort By/Direction
I have a trait for sorting a Livewire data table and I'm now looking to validate the $sortField and $sortDirection query parameters.
I've started to validate $sortDirection in the bootWithSorting() method. $sortDirection defaults to 'asc' if the value is not 'asc' or 'desc'.
This feels like the wrong place and that I should instead be using make validate - although I want to set a sensible default rather than throwing a message - can someone please guide me in the right direction?
Also for $sortFields, I would check that the query parameter is within an array.
<?php
namespace App\Livewire\Concerns;
use Livewire\Attributes\Url;
trait WithSorting
{
#[Url(as: 'sf')]
public $sortField;
#[Url(as: 'sd', except: 'asc')]
public $sortDirection = 'asc';
public function bootWithSorting()
{
if($this->sortDirection <> 'asc' && $this->sortDirection <> 'desc')
{
$this->sortDirection = 'asc';
}
}
public function sortBy(String $field): void
{
if ($this->sortField === $field) {
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
} else {
$this->sortDirection = 'asc';
}
$this->sortField = $field;
}
}
Please or to participate in this conversation.