The code for the policy is here:
class userOwnedClassPolicy
{
use HandlesAuthorization;
...
public function create(User $user)
{
return ($user->userType == 'teacher');
}
...
}
This policy is registered thusly in the AuthServiceProvider.php
file:
class AuthServiceProvider extends ServiceProvider
{
//Map models to authorization policies.
protected $policies = [
App\Models\classMember::class => App\Policies\classMemberPolicy::class,
App\Models\evaluation::class => App\Policies\evaluationPolicy::class,
App\Models\group::class => App\Policies\groupPolicy::class,
App\Models\groupMember::class => App\Policies\groupMemberPolicy::class,
App\Models\sharedClass::class => App\Policies\sharedClassPolicy::class,
App\Models\slg::class => App\Policies\slgPolicy::class,
App\Models\spreadsheet::class => App\Policies\spreadsheetPolicy::class,
App\Models\spreadsheetValue::class => App\Policies\spreadsheetValuePolicy::class,
App\Models\teacher::class => App\Policies\teacherPolicy::class,
App\Models\test::class => App\Policies\testPolicy::class,
App\Models\userOwnedClass::class => App\Policies\userOwnedClassPolicy::class
];
public function boot()
{
$this->registerPolicies();
}
}
(I have tried registering the policies using strings of the file paths as well, but this accomplishes nothing.)
The relevant section of controller code is here:
class ClassController extends Controller
{
...
public function store(Request $postReq)
{
$this->authorize('create', Auth::user());
userOwnedClass::create([
'name' => $postReq->input('className'),
'ownerId' => Auth::user()->id
]);
}
...
}
I have tried substituting the code in the policy's create
method with return true
, but even that fails. What have I done wrong, and why does the controller always return a 403 error when called?
As you created policy
userOwnedClassPolicy
and set it foruserOwnedClass
model inAuthServiceProvider
here:you cannot just run policy method:
When you run this line above, you tell - check
create
method for policy for\App\Models\User
object, but you don't have any policy created for this model.So in this case you should run it like so:
Then Laravel will know that it should run
create
method fromuserOwnedClassPolicy
policy and it will automatically pass currently authenticated user into$user
variable in policy method.