重定向

未匹配的标注
本文档最新版为 2.x,旧版本可能放弃维护,推荐阅读最新版!

After a user performs some action — like submitting a form — you may want to redirect them to another page in your application.

Because Livewire requests aren’t standard full-page browser requests, standard HTTP redirects won’t work. Instead, you need to trigger redirects via JavaScript. Fortunately, Livewire exposes a simple $this->redirect() helper method to use within your components. Internally, Livewire will handle the process of redirecting on the frontend.

If you prefer, you can use Laravel’s built-in redirect utilities within your components as well.

Basic usage

Below is an example of a CreatePost Livewire component that redirects the user to another page after they submit the form to create a post:

<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    public $title = '';

    public $content = '';

    public function save()
    {
        Post::create([
            'title' => $this->title,
            'content' => $this->content,
        ]);

        $this->redirect('/posts'); // [tl! highlight]
    }

    public function render()
    {
        return view('livewire.create-post');
    }
}

As you can see, when the save action is triggered, a redirect will also be triggered to /posts. When Livewire receives this response, it will redirect the user to the new URL on the frontend.

Redirecting to full-page components

Because Livewire uses Laravel’s built-in redirection feature, you can use all of the redirection methods available to you in a typical Laravel application.

For example, if you are using a Livewire component as a full-page component for a route like so:

use App\Livewire\ShowPosts;

Route::get('/posts', ShowPosts::class);

You can redirect to the component by providing the component name to the redirect() method:

public function save()
{
    // ...

    $this->redirect(ShowPage::class);
}

Flash messages

In addition to allowing you to use Laravel’s built-in redirection methods, Livewire also supports Laravel’s session flash data utilities.

To pass flash data along with a redirect, you can use Laravel’s session()->flash() method like so:

use Livewire\Component;

class UpdatePost extends Component
{
    // ...

    public function update()
    {
        // ...

        session()->flash('status', 'Post successfully updated.');

        $this->redirect('/posts');
    }
}

Assuming the page being redirected to contains the following Blade snippet, the user will see a “Post successfully updated.” message after updating the post:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
发起讨论 查看所有版本


暂无话题~