Redirect in Livewire Controller

What seems to be the problem:

Don’t work redirect in Livewire Controller

Steps to Reproduce:

public function test {
return $this->redirect(’/contact-form-success’);
}

or

public function test {
return redirect()->to(’/contact-form-success’);
}

ignoring and working:

public function render(){
return view(‘livewire.test’)
}

Are you using the latest version of Livewire:

2.3.5

Try:

public function test()
{
    return redirect('/contact-form-success');
}

It also doesn’t work

What’s the error you’re getting?

I tried:

component.blade.php

<div> <!-- livewire root element -->
    <button wire:click="test()">
</div>
Component.php

public function test()
{
    return redirect('https://laravel-livewire.com');
}

And that works for me. Maybe you need to put in a FQDN or a named route in the $to portion of redirect($to).

return redirect(url('/contact-form-success'));

The function “Test” invokes from mount() and not from blade.
I try to move “return redirect” to public function mount - redirect not works.
No error. Render works.

I just fired $this->test() in my mount method from my test code (from a couple posts up) and it redirected properly for me. I also just had return redirect('https://laravel-livewire.com'); at the end of the mount() method and it also worked as expected.

Can you paste the entirety of your component and blade code?

make sure that wire:click="test" is inside the view returned by the component AND that the component has a single root element

for me also redirect was not working in livewire component, i took redirect part to controller. i was checking expiry of link.

Controller:

<?php

namespace App\Http\Livewire;

use App\Models\Node;
use Livewire\Component;

class Frontpage extends Component
{
    public $title = 'Test';
    public $content = 'Test';
    public $template_name = 'default';

public function mount($urlslug = null)
    {
        dump($urlslug);
        return redirect('https://laravel-livewire.com');
    }

public function render()
    {
        $nodes = Node::where('parent_id',0)->
        where("is_active", true)->
        where("view_menu", true)->
        get();
        return view('livewire.templates.'.$this->template_name, compact('nodes'))->layout('layouts.guest');
    }
}

blade:

<div>
    <h1>{{ $title }}</h1>
    {!! $content !!}
</div>

web.php:

Route::get('{urlslug}',App\Http\Livewire\Frontpage::class)->where('urlslug', '.*');

If you want to redirect the user in mount method, do it in routes layer, why you are redirecting the user in the mount method?

Route::redirect('{urlslug}', 'https://laravel-livewire.com');'

I need the redirect depending from the urlslug value.

Alright, Try something like this.

public function mount($slug)
{
   $this->slug = $slug;
}

public function render()
{
  if (is_null($this->slug))
     return redirect('url');

 return view('...');
}
<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Frontpage extends Component
{

    public $title = 'Test';
    public $content = 'Test';
    public $template_name = 'default';
    public $slug = '';

public function mount($urlslug = null)
    {
        $this->slug = $urlslug;
    }

public function render()
    {
        if ($this->slug == 'test') {
            return redirect('https://laravel-livewire.com');
        }
        return view('livewire.templates.' . $this->template_name)->layout('layouts.guest');
    }
}

If slug=‘test’ - error:

"render" method on [App\Http\Livewire\Frontpage] must return instance of [Illuminate\View\View]

If slug<>‘test’ - no error, the view is returned.

Can you provide the actual code? Because the idea is not understandable.

returned everything to its original state:

<?php

namespace App\Http\Livewire;

use App\Models\Node;
use App\Models\Page;
use App\Models\Template;
use App\Models\Logdata;
use Carbon\Carbon;
use Livewire\Component;
use Request;

class Frontpage extends Component
{

    public $title = 'Test';
    public $content = 'Test';
    public $template_name = 'default';
    public $debug_text;
    public $nothing = false;
    public $external_URL = '';

    public function mount($urlslug = null)
    {
        $this->nothing = false;
        $this->retrieveContent($urlslug);
    }

    private function getNode($slug,$parent_node_id)
    {
        $node = Node::select('id')->
                      where('node_slug', $slug)->
                      where('parent_id', $parent_node_id)->
                      where('is_active', true)->
                      first();

        if($node) return $node->id;
        else return null;
    }

    private function getDefaultNode()
    {
        $default_node= Node::select('id','node_slug')->where('view_main', true)->first();

        if($default_node) return $default_node;
        else return null;
    }

    private function getPage($slug,$parent_node_id)
    {
        $page = Page::select('id')->
                      where('page_slug',$slug)->
                      where('node_id', $parent_node_id)->
                      where('is_active', true)->
                      first();

        if($page) return $page->id;
        else return null;
    }

    private function getError($node_id, $page_id)
    {
        $this->nothing = true;
    }

    public function retrieveContent($urlslug)
    {
        $default_node = $this->getDefaultNode();

        if($urlslug == '')
        {
            if($default_node) $urlslug = $default_node->node_slug;
        }
        $slugs = explode("/", $urlslug);
        $node_id = 0;
        $page_id = 0;
        $error = false;

        foreach ($slugs as $slug)
        {
            $find_node_id = $this->getNode($slug,$node_id);

            if($find_node_id)
            {
                $node_id = $find_node_id;
                continue;
            }
            else
            {
                if($node_id == 0 && $default_node) $node_id = $default_node->id;
                $page_id = $this->getPage($slug,$node_id);
                if(!$page_id) $error = true;
                break;
            }
        }

        if(!$error)
        {
            $node = Node::find($node_id);
            $this->template_name = $node->template->template_title;

            if($page_id) $page = Page::find($page_id);
            else $page = Page::where('node_id', $node_id)->
                               where('is_default',true)->
                               where('is_active', true)->
                               first();

            if(!$page) goto Fault;

            $this->title = $page->page_title;
            $this->content = $page->page_text;
            $this->debug_text = " node_id=" . $node_id . " page_id=" . $page_id;
            $this->external_URL = $page->page_external;
        }
        else
        {
            Fault: $this->getError($node_id,$page_id);
        }
    }

    public function render()
    {
        if($this->nothing)
        {
            return abort(404);
        }
        else
        {
            if(auth()->user())
            {
                $request = Request();
                $payload = $request->all();

                Logdata::insert(
                    [
                        'user_id' => auth()->user()->id,
                        'ip' => $request->getClientIp(),
                        'ip_x_real' => $request->server('HTTP_X_REAL_IP'),
                        'method' =>  $request->method(),
                        'code' => app('Illuminate\Http\Response')->status(),
                        'url' => $request->url(),
                        'payload' => json_encode($payload),
                        'referer' => $request->server('HTTP_REFERER'),
                        '_server' => json_encode($_SERVER),
                        'created_at' =>  Carbon::now(),
                    ]
                );
            }
            $nodes = Node::where('parent_id',0)->
            where("is_active", true)->
            where("view_menu", true)->
            with('childrenNodes')->
            get();
            // if external URL exists - redirect
            if ($this->external_URL <> '') return redirect($this->external_URL);
            // show page
            return view('livewire.templates.'.$this->template_name, compact('nodes'))->layout('layouts.guest');
        }
    }
}

If external_URL <> ‘’ then Exception
"render" method on [App\Http\Livewire\Frontpage] must return instance of [Illuminate\View\View]

Redirect is work !

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Test extends Component
{
    public $title = 'Test';
    public $content = 'Test content';
    public $template_name = 'default';
    public $debug_text;
    public $nothing = false;
    public $external_URL = '';

    public function mount($slug = null)
    {
        $this->nothing = false;
        $this->retrieveContent($slug);
    }

    public function retrieveContent($slug)
    {
        return redirect('https://laravel-livewire.com');
    }

    public function render()
    {
        return view('livewire.test')->layout('layouts.guest'); 
    }
}

Redirect is NOT work ! View return!!!

<?php

    namespace App\Http\Livewire;

    use Livewire\Component;

    class Test extends Component
    {
        public $title = 'Test';
        public $content = 'Test content';
        public $template_name = 'default';
        public $debug_text;
        public $nothing = false;
        public $external_URL = '';

        public function mount($slug = null)
        {
            $this->nothing = false;
            $this->retrieveContent($slug);
        }

        public function retrieveContent($slug)
        {
            return redirect('https://laravel-livewire.com');
        }

        public function render()
        {
            return view('livewire.templates.default')->layout('layouts.guest');
        }
    }

Differences in render:

return view(‘livewire.test’)->layout(‘layouts.guest’);
and
return view(‘livewire.templates.default’)->layout(‘layouts.guest’);

‘livewire.test’ and ‘livewire.templates.default’ exists.

Seemingly the reason is in view livewire.templates.default.
View has @section(‘content’) - If I delete a section the redirect works.

1 Like