Reputation: 497
I'm implementing roles and permission for a project, and using policies, but I have a problem when I want to authorize or not the creation of new records in the patients table, very simple stuff. I have this in my PatientPolicy
// Only the users with root or admin roles can create patients;
public function create(User $user){
return ($user->hasRole('root') || $user->hasRole('admin'));
}
// only the patient creator can edit the patient and see the edit button
public function update(User $user, Patient $patient){
return $user->id == $patient->user_id;
}
AuthServiceProvider
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
'App\Patient' => 'App\Policies\PatientPolicy'
];
PatientController
public function edit(Patient $patient){
if(Gate::denies('update', $patient)){
abort(403, 'No esta autorizado de estar aqui');
}
return view('patients.edit', compact('patient'));
}
public function create(){
if(Gate::denies('create')){
abort(403, 'Usted no esta autorizado para crear pacientes');
}
return view('patients.create');
}
and in my views
@can('create')
<li class="header">PROCESOS</li>
<li><a href="/paciente/create"><i class="fa fa-book"></i> <span>Apertura de Historia Clínica</span></a></li>
@endcan
The problem is that the create policy is always returning false even for those users that are suppossed to be allowed to perform the action, however the edit policy works perfectly. Am I missing something?
Upvotes: 3
Views: 464
Reputation: 9049
The problem is Gate::denies
and @can
methods don't know which model and policy class they should look for when there is no argument to correspond, so use this code instead:
public function create(){
if(Gate::denies('create', Patient::class)) {
abort(403, 'Usted no esta autorizado para crear pacientes');
}
return view('patients.create');
}
and in your views:
@can('create', App\Patient::class)
<li class="header">PROCESOS</li>
<li><a href="/paciente/create"><i class="fa fa-book"></i> <span>Apertura de Historia Clínica</span></a></li>
@endcan
You can check my full answer here: https://stackoverflow.com/a/37261276/3477084
Upvotes: 1