Laravel 8 - 如果用戶有權調用路由,請簽入控制器 (Laravel 8 - Check in Controller if user has permission to call route)


問題描述

Laravel 8 ‑ 如果用戶有權調用路由,請簽入控制器 (Laravel 8 ‑ Check in Controller if user has permission to call route)

我有一個類來創建我的導航並且我使用 spatie 權限。現在我想在我定義的路線的幫助下建立導航。是否可以在構建導航之前檢查用戶是否可以訪問路線?


參考解法

方法 1:

Yes you can able to check permission of users. Below are the methods available in spatie permissions.

$user‑>hasPermissionTo('edit articles');

You can check if a user has Any of an array of permissions:

$user‑>hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

...or if a user has All of an array of permissions:

$user‑>hasAllPermissions(['edit articles', 'publish articles', 'unpublish articles']);

You can refer this link

$user is basically your auth()‑>user()

方法 2:

I am using Laravel 8.x version.

We can check the given permission in controller file eg:

if(Auth::user()‑>can('product_view')){
    // allowed statement will be here
}

while given permission can be checked in view blade file eg:

@can('product_view')
    // allowed statement will be here
@endcan

We can also check permission in routes/web.php file:

Route::get('/products/productdetail', [ProductsController::class, 'productdetail'])‑>name('products.productdetail')‑>middleware('can:product_view');

Thanks a lot for asking this question. Happy to help :)

(by Robert FelsTansukh RathodKamlesh)

參考文件

  1. Laravel 8 ‑ Check in Controller if user has permission to call route (CC BY‑SA 2.5/3.0/4.0)

#laravel-8 #Laravel






相關問題

在 Laravel 的表中計算 user_id (Count user_id in a table in Laravel)

如何通過模型顯示表中的數據,自定義行除外 (How to show data from table via Model except a custom row)

如何在 Laravel 的模型中為所有貨幣字段(十進制屬性)加上逗號 (How to put comma to all money fields (decimal attributes) in a model in Laravel)

Laravel:8.x 目標類 [ArticlesController] 不存在 (Laravel:8.x Target class [ArticlesController] does not exist)

如何根據 laravel 中的一列獲取最新記錄? (How to get latest record based on one column in laravel?)

訂閱者中間件路由允許公眾查看所有受限頁面 (Subscriber middleware route allowing public to view all restricted pages)

更改徽標默認通知電子郵件 laravel 8 (change logo default notification email laravel 8)

Laravel 8 - 如果用戶有權調用路由,請簽入控制器 (Laravel 8 - Check in Controller if user has permission to call route)

laravel 微風 Multi Auth - 具有兩個不同註冊的 Admin Guard (laravel breeze Multi Auth - Admin Guard with two diffirent registration)

找不到組件的類或視圖 (Unable to locate a class or view for component)

Laravel 8 數據庫不會使用 HTML 表單更新 (Laravel 8 database won't update using HTML form)

Laravel問題從電子郵件驗證傳遞錯誤消息 (Laravel problem to pass error message from email verification)







留言討論