【Laravel實戰】10分鐘搞懂Livewire的轉址功能

【Laravel實戰】10分鐘搞懂Livewire的轉址功能

你可能想要透過 Livewire 組件讓你在應用裡去轉址到其他頁面,Livewire 支持你用在 Laravel 控制器的標準轉址回應語法

//app/Http/Livewire/ContactForm.php

class ContactForm extends Component
{
    public $email;

    public function addContact()
    {
        Contact::create(['email' => $this->email]);

        return redirect()->to('/contact-form-success');
    }
}
//resources/views/livewire/contact-form.blade.php
<div>
    Email: <input wire:model="email">

    <button wire:click="addContact">Submit</button>
</div>

現在,當使用者點下 "submit"按鈕且聯絡單的內容寫入資料庫之後,使用者將會被轉到成功頁面(/contact-form-success)

而且因為 Livewire 搭配 Laravel的轉址系統在運作,你可以使用所有先前在 Laravel 所用過的寫法,像是redirect('/foo'), redirect()->to('/foo'), redirect()->route('foo')

快閃訊息

假如你需要顯示成功或者是錯誤的訊息讓使用者知道,Livewire 採用和 Laravel 相同的做法,也就是將快閃資料存在 Session 裡頭

這是一個常見的快閃訊息例子:

//app/Http/Livewire/UpdatePost.php

class UpdatePost extends Component
{
    public Post $post;

    protected $rules = [
        'post.title' => 'required',
    ];

    public function update()
    {
        $this->validate();

        $this->post->save();

        session()->flash('message', '文章更新成功!!');
    }
}
//resources/views/livewire/update-post.blade.php

<form wire:submit.prevent="update">
    <div>
        @if (session()->has('message'))
            <div class="alert alert-success">
                {{ session('message') }}
            </div>
        @endif
    </div>

    Title: <input wire:model="post.title" type="text">

    <button>Save</button>
</form>

現在,當使用者按下 "Save" 按鈕且文章被更新之後,使用者將會看到 "文章更新成功!!" 的這個訊息顯示在頁面上

假如你想要的是轉址到目標頁面才顯示訊息的話, Livewire 會很聰明的為你保留這個快閃訊息到下一個請求,下面是一個例子:

public function update()
{
    $this->validate();

    $this->post->save();

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

    return redirect()->to('/posts');
}

現在當使用者儲存一個文章,他們將會被轉址到 "/posts" 這個網址,然後在那個頁面看到快閃訊息。當然這前提是 "/posts" 頁面具有支持的 Blade 程式片段用來顯示快閃訊息才行

快閃套件

什麼? 你覺得還要自己搞定 Flash Message 的前端效果太麻煩,我聽到你的聲音囉

不管你是希望在 Laravel Blade 頁面 又或者是在 Livewire 組件上去顯示快閃訊息,都有對應的套件來幫你搞定呈現面的功能,請看10分鐘做出LARAVEL的FLASH MESSAGE訊息顯示


分享這篇文章:

關聯文章:

訂閱電子報,索取 Laravel 學習手冊

價值超過 3000 元,包含常用 Laravel 語法與指令!

Laravel 百萬年薪特訓營

從最基礎的 PHP 語法開始,包含所有你該知道的網頁基礎知識,連同 Laravel 從零開始一直到實戰,最後還將告訴你如何找好工作,讓你及早擁有百萬年薪