【Laravel實戰】3分鐘搞懂Livewire的授權功能

【Laravel實戰】3分鐘搞懂Livewire的授權功能

要在 Livewire 進行授權的驗證,你能夠在任何組件裡頭去使用 AuthorizesRequests trait,接著在行動中去呼叫 $this->authorize(),就如同以前在控制器裡頭那樣的寫法,例如:

//app/Http/Livewire/EditPost.php

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class EditPost extends \Livewire\Component
{
    use AuthorizesRequests;

    public $post;

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

    public function save()
    {
        $this->authorize('update', $this->post);

        $this->post->update(['title' => $this->title]);
    }
}

看起來 Livewire 採用了與 Laravel 相同的授權機制,如需了解 Laravel官方授權機制,請參考這裡

假如你使用了不同的 guard 來驗證你的使用者,那麼你也要加入一個實體到 livewire 設定檔的 middleware_group:

//config/livewire.php
...
'middleware_group' => ['web', 'auth:otherguard'],
...

分享這篇文章:

關聯文章:

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

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

Laravel 百萬年薪特訓營

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