問題描述
如何通過模型顯示表中的數據,自定義行除外 (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 user10502851、Ben Gooding、jiedevm)