Redirect in updated

I have a search component and when the user is not on the homepage I’d like to redirect to the homepage. But this redirect doesn’t work. How can I fix that ?

class Search extends Component
{
    public $q = '';

    public $currentRouteName = '';

    protected $updatesQueryString = ['q'];

    public function updatedQ ()
    {
        if ($this->currentRouteName !== 'home') {
            return redirect()->route('home', ['q' => $this->q]);
        }
        
        $this->emit('search', $this->q);
    }

    public function mount ()
    {
        $this->q = request('q', '');
        $this->currentRouteName = Route::currentRouteName();
    }

    public function render()
    {
        return view('livewire.layout.search');
    }
}

Try this: (untested)

redirect()->to(route('home', ['q' => $this->q]));

Unfortunately that doesn’t work, it’s the same as:
return redirect()->route(‘home’, [‘q’ => $this->q]);

Remove the “return” keyword, use this: redirect(’/home’);

Thanks, but this still doesn’t work :frowning: When I look in the response of the livewire request, the RedirectTo field is still false.

class Search extends Component
{
    public $q = '';

    public $currentRouteName = '';

    protected $updatesQueryString = ['q'];

    public function updatedQ ()
    {
        if ($this->currentRouteName !== 'home') {
            redirect()->route('home', ['q' => $this->q]);
        }
    }

    public function mount ()
    {
        $this->q = request('q', '');
        $this->currentRouteName = Route::currentRouteName();
    }

    public function render()
    {
        return view('livewire.layout.search');
    }
}

instead of just using redirect, try to use $this->redirect()

@vittorioe

I had the same issue as @raydotnl.

Your answer helped fixing it!

But, using $this-> comes with other issues, which fortunately are easily to circumvent.

When using $this-> it is not possible to chain redirect() with to() or route(), like mentioned in the Livewire documentation https://laravel-livewire.com/docs/redirecting.

So the following doesn’t work: return $this->redirect()->to('/target')

But luckily this does work: return $this->redirect('/target')