What exactly are you looking to ask here?
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
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.
Remove the admin user from the collection before you pass it to the view.
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?
use REJECT
as in:
$nonAdminUsers = $users->reject(function ($user) {
return Auth::user()->hasRole('admin');
};
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]
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
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'));
}
I want to get all the users except the AUTH admin
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
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'));
}
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'));
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'.
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'));
}
Thanks a lot for answer, but now i get 'Invalid argument supplied for foreach()', any idea?
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. ?
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.
All right let's see you blade file something is screwy
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
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.
yep, i have filp whoops installed and env set for debug.
It says that sth wrong is with
$users = User::whereNotIn('id', $user->id);
You're not executing the query. You need to use
$users = User::whereNotIn('id', $user->id)->get();
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 !!!
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
Thank you for your patience and commitment, but after add '->get()' unfortunately it still doesn't work and i get the same error.
@RamjithAp it works for all users with admin role, but i want to hide only AUTH user with this role :)
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'));
}
@RamjithAp Oh thanks a lot, it works like i want!
@robrogers3 thank you too for help and patience! @sutherland in the next project i will use policies as you suggested, thanks for advice.
Query Should Be
$user = User::where('id','!=',Auth::user()->id)->get();
Please or to participate in this conversation.