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


問題描述

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

我在我的項目中使用 Laravel 8,在這個項目中,我製作了一個管理員創建用戶的頁面。

基本上,每個用戶都有一個角色,所以為了顯示角色,我已經添加了這個:

<div class="form‑group">
   <label class="col‑sm‑2 control‑label">Role</label>
   <select class="form‑control" name="role" dir="ltr">
   @foreach(\App\Models\Role::all() as $role)
      <option value="{{ $role‑>id }}">{{ $role‑>name }}</option>
   @endforeach
   </select>
</div>

所有角色都是這樣的:

在此處輸入圖片描述

現在我不想在這個表單域中打印 Super Admin。所以我的問題是,如何防止 \App\Models\Role::all() 在選擇選項中打印超級管理員?

我非常感謝任何想法或建議來自你們……<


參考解法

方法 1:

Instead of using all, you could do something like where('name', '!=', 'SuperAdmin')‑>get() or whereNotIn('name', [...hidden_roles])‑>get()

Now this should also be in your controller as the view shouldn't be interested with the business logic

Even better create a method in your user model called something like getNonAdminRoles (and you can add to this later if there are more hidden roles), or a more laravel way and create a scope https://laravel.com/docs/8.x/eloquent#local‑scopes

方法 2:

You can do something like this in the view:

 <div class="form‑group">
   <label class="col‑sm‑2 control‑label">Role</label>
     <select class="form‑control" name="role" dir="ltr">
     @foreach(\App\Models\Role::all() as $role)
       @if($role‑>slug != 'super‑admin')
         <option value="{{ $role‑>id }}">{{ $role‑>name }}</option>
       @endif
     @endforeach
     </select>
 </div>

(by user10502851Ben Goodingjiedevm)

參考文件

  1. How to show data from table via Model except a custom row (CC BY‑SA 2.5/3.0/4.0)

#laravel-8 #Laravel #PHP






相關問題

在 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)







留言討論