Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tomu1202's avatar

Hide admin user in view

Don't show below user in view:

//Auth::user()->hasRole('admin'))
            @foreach($users as $index => $user)
                <tr>
                                    <td>{{ $index +1}}</td>
                                    <td>{{$user->name}}</td>
                                    <td>{{$user->surname}}</td>
                                    <td>{{$user->roles->first()->role}}</td>
                                    <td>{{$user->department}}</td>
                                    <td>
                </tr>
            @endforeach     
0 likes
28 replies
tomu1202's avatar

I would like to disable show: Auth::user()->hasRole('admin')) in the table above, for example due to sign in admin can't delete himself.

squibby's avatar

Remove the admin user from the collection before you pass it to the view.

tomu1202's avatar
    public function manage(Request $request)
    {
        //Check role
        $request->user()->authorizeRoles('admin');

        $auth_admin_user = Auth::user()->hasRole('admin');
        $users = User::all();
        $users->except($auth_admin_user);

        return view('users.manage')->with('users', $users);
    }

error: "array_key_exists(): The first argument should be either a string or an integer"

when i use 'forget()' instead of 'except()', there are no errors but auth admin is still show in the table.

how to use 'except()' in correct way?

robrogers3's avatar

use REJECT

as in:

$nonAdminUsers = $users->reject(function ($user) {

    return  Auth::user()->hasRole('admin');
};
1 like
robrogers3's avatar

ps. except just uses an array key.

$collection = collect(['product_id' => 1, 'price' => 100, 'discount' => false]);

$filtered = $collection->except(['price', 'discount']); //THESE ARE KEYS

$filtered->all();

// ['product_id' => 1]

tomu1202's avatar

Thank you for answering my question, but now when i use REJECT in this way

    public function manage(Request $request)
    {
        //Check role
        $request->user()->authorizeRoles('admin');

        $users = User::all();

        $usersWithoutAuthAdmin = $users->reject(function ($user){
            return Auth::user()->hasRole('admin');
        });
        
        return view('users.manage')->with('users', $usersWithoutAuthAdmin);
    }

this returns nothing

JasperWelsing's avatar

If I understand your question correctly and you want to get all the users except the admin(s) I think this should do the trick :

public function manage(Request $request)
    {
        $users = User::where('role', '!=', 'admin')->get();

        return view('users.manage', compact('users'));
    } 
tomu1202's avatar

I want to get all the users except the AUTH admin

sutherland's avatar

If you don't want an admin to be able to delete their own account, a much better way of doing it would be using policies. You'd only need to write the logic to check if a user has permission to delete a user once then be able to use it in your views and to protect against it at the controller level.

You'd need to write a UserPolicy with a delete method like this:

    public function delete(User $authenticated, User $user)
    {
        if ($authenticated->hasRole('admin') && $authenticated->id !== $user->id) {
            return true;
        }

        return false;
    }

Then in your controller method to delete a user you can use this:

$this->authorize('delete', $user);

And finally in your view:

@can('delete', $user)
    <!-- Delete button goes here -->
@endcan

Here's the docs on policies: https://laravel.com/docs/5.5/authorization#creating-policies

2 likes
JasperWelsing's avatar

Try this:

public function manage(Request $request)
    {
        $auth_admin_user = Auth::user()->hasRole('admin')->pluck('id');
        $users = User::whereNotIn('id', $auth_admin_user)->get();

        return view('users.manage', compact('users'));
    } 
1 like
robrogers3's avatar

yep. @JasperW is probably right.

but if you want to use the collection. you need hasRole()->empty(); //or ->count(); can't remember off hand.

well it depends what the hasRole method returns too.

what does this say dd(Auth::user()->hasRole('admin'));

1 like
tomu1202's avatar

Trying to do it in @JasperW way i get error 'Call to a member function pluck() on boolean'

My role functions:

    public function authorizeRoles($roles)
    {
      if (is_array($roles)) 
      {
        if($this->hasAnyRole($roles))
        {
          return $this->hasAnyRole($roles);          
        }else{
          abort(403);
        }
      }

      if($this->hasRole($roles)){
        return $this->hasRole($roles);
      }else{
        abort(403);
      }
    }

    /**
    * Check multiple roles
    * @param array $roles
    */

    public function hasAnyRole($roles)
    {
      return null !== $this->roles()->whereIn('role', $roles)->first();
    }

    /**
    * Check one role
    * @param string $role
    */

    public function hasRole($role)
    {
      return null !== $this->roles()->where('role', $role)->first();
    }

Maybe it's important to say that i have three tables: 'users', 'roles' and intermediary table 'role_user'.

robrogers3's avatar

this is because $user = Auth::user()->hasRole('admin') is a boolean.


public function manage(Request $request)
    {
        $user = Auth::user();
    //a little ugly
        if ($user->hasRole('Admin')) {
            $users = User::whereNotIn('id', $user->id);
        } else {
            $users = User::all();
        }

        return view('users.manage', compact('users'));
    } 

tomu1202's avatar

Thanks a lot for answer, but now i get 'Invalid argument supplied for foreach()', any idea?

robrogers3's avatar

That's because it's returning null or something back

dd($users and see what you find.

If you get null then we can just cast it to an array. Easy.

But it is weird that either query returns null. How many users do you have in the database. ?

tomu1202's avatar

i did 'php artisan migrate:fresh --seed', so now i have only free users from seeders 'admin', 'serviceman' and 'employee'. Admin id = 1. I get still the same error. After use dd($users), it returns all users.

robrogers3's avatar

All right let's see you blade file something is screwy

tomu1202's avatar

It's my fragment of blade file

                    <h3>All Users</h3>
                    @if(count($users) > 0)
                        <table class="table table-hover" id="delete-confirm">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Name</th>
                                    <th>Surname</th>
                                    <th>Role</th>
                                    <th>Department</th>
                                    <th></th>
                                    <th></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($users as $index => $user)
                                    <tr>
                                        <td>{{$index +1}}</td>
                                        <td>{{$user->name}}</td>
                                        <td>{{$user->surname}}</td>
                                        <td>{{$user->roles->first()->role}}</td>
                                        <td>{{$user->department}}</td>
                                        <td>
                                            <a href="/users/{{$user->id}}" class="w3-btn w3-ripple w3-blue w3-round-large pull-right"><span class="glyphicon glyphicon-info-sign"></span> Details</a>
                                        </td>
                                        <td>
                                            <a href="/users/{{$user->id}}/edit" class="w3-btn w3-ripple w3-green w3-round-large pull-right"><span class="glyphicon glyphicon-pencil"></span> Edit</a>
                                        </td>
                                        <td>
                                        {!! Form::model($user, ['method' => 'delete', 'route' => ['users.destroy', $user->id], 'class' =>'form-delete']) !!}
                                            {!! Form::hidden('id', $user->id) !!}
                                            {!! Form::button('<span class="glyphicon glyphicon-trash"></span> Delete', ['type' => 'submit','class' => 'w3-btn w3-ripple w3-red w3-round-large pull-right'])!!}
                                        {!! Form::close() !!}
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    @else
                        <p>No users here</p>
                    @endif
robrogers3's avatar

By the way do you have flip whoops installed. And is you env set for debug ?

That would make this much easier to figure out.

sutherland's avatar

You're not executing the query. You need to use

$users = User::whereNotIn('id', $user->id)->get();
robrogers3's avatar

Damn I'm an idiot I can't believe I missed the missing get.

That's the problem. As soon as I saw flip whops.

So after the where add a ->get()

Fixed !!!

RamjithAp's avatar

Simply use if condition in your view

   @foreach($users as $index => $user)
   @if(!$user->admin){ 
                <tr>
                                    <td>{{ $index +1}}</td>
                                    <td>{{$user->name}}</td>
                                    <td>{{$user->surname}}</td>
                                    <td>{{$user->roles->first()->role}}</td>
                                    <td>{{$user->department}}</td>
                                    <td>
                </tr>
   @endif
   @endforeach    
tomu1202's avatar

Thank you for your patience and commitment, but after add '->get()' unfortunately it still doesn't work and i get the same error.

https://snag.gy/pgtQ97.jpg

@RamjithAp it works for all users with admin role, but i want to hide only AUTH user with this role :)

RamjithAp's avatar
Level 10

Then you are not supposed to use the whereNotIn class because you were not passing an array. Try this

public function manage(Request $request)
    {
        $user = Auth::user();
        if ($user->hasRole('Admin')) {
            $users = User::where('id', '!=',$user->id)->get();
        } else {
            $users = User::all();
        }
        return view('users.manage', compact('users'));
    } 
Shakhawat's avatar

Query Should Be

$user = User::where('id','!=',Auth::user()->id)->get();

Please or to participate in this conversation.