Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ella-stinnes's avatar

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;
    }
}
0 likes
0 replies

Please or to participate in this conversation.