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

Sabonzy's avatar

Livewire - array to comma separated for query string

I have an array property topic on a livewire component that I want to use as query string, the query string looks like this currently example.com/?topic[0]=livewire&topic[1]=laravel,

but I prefer the url to look like this example.com/?topic=livewire,laravel

currently I introduce a seperate property queryStringTopic and convert the topic array to comman separated string

public array topic = [];

#[Url(as: 'topic',except:'')]
public string $queryStringTopic='';

public function updatedTopic()
{
   $this->queryStringTopic = implode(',',$this->topic);
 }

and convert it back to an array in the mount method and assign it to the topic property.

public function mount()
{
   if (! empty($this->queryStringTopic)) 
	{
      $this->topic = explode(',', $this->queryStringTopic);
	}
 }

Is there a better way to achieve this?

0 likes
3 replies
jlrdw's avatar

PHP has this already, http_build_query.

Like:

return $this->params != null ?  '?' . $this->instance . "=" . $this->getInstance() . '&' . http_build_query($this->params) : null;

It turns this:

'params' => ['psch' => $dogsearch, 'aval' => $aval]

into a query string. I.e.,

?page=2&psch=c&aval=n
Sabonzy's avatar

@jlrdw Thanks for the response but I'm struggling to grasp it, $this->instance and $this->getInstance() is it a reference to the livewire component.

the http_build_query() includes the array's key in the query string, instead of ?page=2&psch=c&aval=n I want ?page=2&topic=c,n

jlrdw's avatar

@Sabonzy No, that was just an example from my code. Lookup http_build_query() in the php manual to learn it's usage.

1 like

Please or to participate in this conversation.