I'm currently trying to find out if you can add a Gate Fascade to a Policy or if there's a better way to handle my situation.
I have a list of users with each having ONE role and each role can have MANY permissions. All of this is stored in my database with the correct relationships established in my models.
I am trying to show or not show a delete icon based on whether a user can delete another user in my HTML list of users.
Example:
Lets say user1 has a role of 3 which is a site-admin. Site admins have the permission to delete users, however they are NOT able to delete other users who have the same role as them or a role higher than theirs.
When user1 accesses the /users uri they are shown the HTML table of users in the database and as the last table column are the actions that can be performed on the row for that user row. The available action icons are edit and delete. For the delete icon I want a policy to be ran to make sure than the authenicated user can delete users first but also pass the current row's user object and see if the user has the same role id or higher in which case it will NOT display that icon.
<?php
namespace App\Policies;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class UserPolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* @return void
*/
public function __construct()
{
//
}
public function delete(User $user) {
return Auth::user()->role->permission and $user->role_id < Auth::user()->role_id and $user->id != Auth::user()->id;
}
}
/reources/views/partials/tables/actions.blade.php
<td class="actions">
<a href="{{ route('users.edit', $user->id) }}" class="btn btn-sm btn-icon btn-pure btn-default" data-toggle="tooltip" data-original-title="Edit"><i class="icon wb-edit" aria-hidden="true"></i></a>
<a href="{{ route('users.show', $user->id) }}" class="btn btn-sm btn-icon btn-pure btn-default" data-toggle="tooltip" data-original-title="Show"><i class="icon wb-eye" aria-hidden="true"></i></a>
@can('delete-user', $user)
<form class="inline" method="POST" action="{{ route('users.delete', [$user->id]) }}">
{{ method_field('DELETE') }}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-sm btn-icon btn-pure btn-default on-default" data-toggle="tooltip" data-original-title="Delete"><i class="icon wb-trash" aria-hidden="true"></i></button>
</form>
@endcan
</td>
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire