How to show data from table via Model except a custom row

Viewed 110

I'm using Laravel 8 for my project and in this project, I have made a page for creating users by admins.

And basically, each user has a role, so in order to show the roles, I have added this:

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

And all of roles goes like this:

enter image description here

Now I don't want to print Super Admin in this form field. So my question is, how can I prevent \App\Models\Role::all() from printing Super Admin in select option?

I would really appreciate any idea or suggestion from you guys...

Thanks in advance.

2 Answers

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

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>
Related