簡體   English   中英

如何在 Laravel 中使用 spatie 權限中間件?

[英]How to use spatie permission middleware in Laravel?

我正在使用 Laravel 8 和 Spatie 角色和權限。 每個操作的權限都可以正常工作。 但是,如果我將刪除操作權限分配給子管理員,但我直接從 URL middlware 中點擊創建操作,則由於用戶沒有創建權限,因此無法停止操作。

 public function __construct(CustomerInterface $customerInterface)
{
    $this->customerInterface = $customerInterface;
    $this->middleware(['permission:create_customer|delete_customer|edit_customer|chnage_customer_status']);
}

我在構造函數中使用上述中間件。 我該如何解決這個問題。

文檔中我可以看出,當您使用具有多個權限的permission中間件時,如果至少有一個權限簽出,它將讓請求繼續進行。

您需要的是基於方法的授權,為此,Laravel 使用策略,默認情況下允許您為常用方法編寫單獨的授權。 (索引、存儲、更新、顯示等)

假設您讓用戶僅在擁有create_customer權限的情況下使用store方法,您的策略將如下所示:

    /**
     * Determine whether the user can create models.
     *
     * @param User $user
     * @return mixed
     */
    public function create(User $user)
    {
        return $user->can('create_customer');
    }

然后在 controller 中,放置authorizeResource function ,它將默認策略方法與默認資源 controller 方法相關聯:

    public function __construct(CustomerInterface $customerInterface)
    {
        $this->customerInterface = $customerInterface;
        $this->authorizeResource(Customer::class); // assuming your model name is Customer
    }

或者,您可以編寫自己的自定義策略方法並通過$this->authorize方法使用它們,該方法在此處進一步記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM