I have an Employer model + controller + policy, all located and named as per the docs and the policy is auto-detected and implemented as expected just fine. Well sort of, using the code below, 'view' is authorized ok, but 'create' is not (is always 'unauthorized').
class EmployerPolicy
{
public function view(User $user, Employer $employer): bool
{
return true;
}
public function create(User $user): bool
{
return true;
}
}
class EmployerController extends Controller
{
public function show(Employer $employer)
{
Gate::authorize('view', $employer);
return view('employer.show', ['employer'=> $employer]);
}
public function create()
{
Gate::authorize('create');
return view('employer.create');
}
}
The only way I can get it to work is by passing an Employer object into the policy, something like below (for 'create'):
class EmployerPolicy
{
public function view(User $user, Employer $employer): bool
{
return true;
}
public function create(User $user, Employer $employer): bool
{
return true;
}
}
class EmployerController extends Controller
{
public function show(Employer $employer)
{
Gate::authorize('view', $employer);
return view('employer.show', ['employer'=> $employer]);
}
public function create()
{
$employer = new Employer();
Gate::authorize('create', $employer);
return view('employer.create');
}
}
I haven't seen this behaviour mentioned anywhere, in my mind if the policy file is auto-detected then any of the policy methods should work, but it appears that it only works when an instance of the model is passed into 'authorize'.
Is this expected behaviour?