Support the ongoing development of Laravel.io →
posted 8 years ago
Blade
Last updated 2 years ago.
0

I had the same problem, if you define a create policy inside a policy class it doesn't seem to work because since you reference in AuthServiceProvider the policy related to a model, laravel expects to have an instance of the model as parameter. The way I solved it is placing just the create policy directly in the AuthServiceProvider instead of inside the Policy.

For example in my PatientPolicy:

// only the root and admin can edit the patient and see the edit button
public function update_patient(User $user, Patient $patient){
    return ($user->hasRole('root') || $user->hasRole('admin'));
}

// only the root and admin can edit the patient and see the edit button
public function delete_patient(User $user, Patient $patient){
    return ($user->hasRole('root') || $user->hasRole('admin'));
}

and my AuthServiceProvider

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    'App\Patient' => 'App\Policies\PatientPolicy',
];

public function boot(GateContract $gate)
{
    $this->registerPolicies($gate);

    $gate->define('create_patient', function($user){
        return $user->hasRole('root') || $user->hasRole('admin');
    });
}
0

Hello,

Thank you for your reply. So this means that "index", "create", "store" method will be in the Provider while "edit", "update" and "destroy" will be in the Policy class? The point of using Policies is to reunite the ACL's of a given object at the same place. I really surprised Laravel doesn't provide such a feature.

Actually, the official method works at least partially. In my controller, I use:

// For index, create and store
$this->authorize('index', Project::class);

and

// For edit, update, destroy
$this->authorize('show', $project);

It works really fine.

The only problem I have is in the blade view:

@can('create', Project::class)
    <a class="btn btn-primary" href="">Add a mockup</a>
@endcan

Laravel doesn't seem to load the Policy for Project::class. So permission is never granted.

Thanks again,

A.

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

AxelOz axeloz Joined 11 Dec 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.