Optional parameter(s) on a Livewire route

In Laravel, it is possible to have optional parameters on the route.

{token?}

How can I achieve this with a Livewire route?

Route::livewire(’/register/{token?}’, ‘auth.register’)->layout(‘layouts.app’)->name(‘auth.register’);

Users can register by themselves, if the app is set to invite only then I need to pass in the token to check if the invite is valid. I have looked at the official documentation but I couldn’t find anything. I might of missed something though.

Setting a default for $token using the mount method would work but I still have to pass something to the route.

/register/new

Just pull it out of the request().

public $token

public function mount()
{
    $this->token = request()->token; // this takes into account your optional parameter is named token 
}

Then you can access the $this->token wherever you need to get the token.

2 Likes

Good idea. That makes sense. I was totally overthinking it. I assume the Livewire route will just be:

/register

Then when I need to pass the token to the route I just append it?

/register/token

Could also do it this way:

/register?token=token

Actually I’ll have to do it this way, how else is request() going to know what the token is?

If you make your livewire route to just

Route::livewire('/register/{token?}', 'livewire-component')->layout('layout')->name('route.name');

Then check to see if token is null. If it’s null, there’s no token passed. This way you don’t have to have too many routes cluttering things up.

You can go query strings if you like. It’s a stylistic thing but I think params look a little more clean.

1 Like

That is what I was trying originally. The optional parameter doesn’t work, and that is without adding any logic into the Livewire component.

Update: I just tried it again, I must of made a mistake somewhere as it works now. Strange as I just did what I originally explained in my first post.