This may seem a simple problem, but I could not find a solution either in Laravel policy documentation or in Spatie/Laravel-permission documentation.
Here is the problem:
This is how I've assigned permissions to certain roles in PermissionSeeder.php:
public function run()
{
// Reset cached roles and permissions
app()[PermissionRegistrar::class]->forgetCachedPermissions();
// create permissions
Permission::create(['name' => 'view own tickets']);
Permission::create(['name' => 'view all tickets']);
Permission::create(['name' => 'forward a ticket']);
Permission::create(['name' => 'close a ticket']);
Permission::create(['name' => 'write a ticket']);
Permission::create(['name' => 'assign permissions to roles']);
Permission::create(['name' => 'hide a ticket']);
// create roles and assign existing permissions
$role1 = Role::create(['name' => 'staff']);
$role1->givePermissionTo('view own tickets');
$role1->givePermissionTo('forward a ticket');
$role1->givePermissionTo('close a ticket');
$role1->givePermissionTo('write a ticket');
$role2 = Role::create(['name' => 'admin']);
$role2->givePermissionTo('view own tickets');
$role2->givePermissionTo('forward a ticket');
$role2->givePermissionTo('close a ticket');
$role2->givePermissionTo('write a ticket');
$role2->givePermissionTo('hide a ticket');
$role2->givePermissionTo('view all tickets');
$role3 = Role::create(['name' => 'Super-Admin']);
}
Now let me give you an example of how my controller method for forwarding a method looks:
class TicketController extends Controller
{
/**
* forward a ticket to another user.
*
* @param Request $request
* @return Response
*/
public function forwardTo(Request $request)
{
$ticket = TicketTitle::find($request->ticket_id);
$ticket->forwarded_to = $request->user_id;
$ticket->status = TicketTitle::STATUS_FORWARDED;
$ticket->save();
return \response($ticket, 200);
}
}
It is necessary to first verify that the user has the permission to forward a ticket before executing this method... Could you please explain how to do this?
If I have to define a policy, given the name of my method and my permission, what should the policy be called?
I also checked similar questions, but none of them had the answer I was looking for.
CodePudding user response:
You can from method: has Permission To Use as follows:
$user->hasPermissionTo('edit articles')
CodePudding user response:
if(auth()->user()->hasPermissionTo('forward a ticket')){
$ticket->forwarded_to = $request->user_id;
};
try this one.commit for further issues