dimanche 17 juin 2018

Applying Laravel Policies: $this->authorizeResource('model'); is required in the controller's constructor?

I have UserPolicy:

<?php

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    public function create(User $user)
    {
        return $user->can('create_users');
    }

    public function update(User $user, User $model)
    {
        return $user->can('edit_users');
    }

    public function delete(User $user, User $model)
    {
        return $user->can('delete_users');
    }
}

and it is registered in AuthServiceProvider:

protected $policies = [
    User::class => UserPolicy::class,
];

On the other side I have UserController with create, update, destroy methods.

But UserPolicy doesn't work, it's not applied - I am still able to create, edit/update...

If I add $this->authorizeResource('user'); in the __construct() of UserController - then policies work and I cannot create/update/delete:

class UserController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource('user');
    }

But, is this the right way to do it?

If I understood Laravel's documentation well, only registering a policy in AuthServiceProvider:

   protected $policies = [
        User::class => UserPolicy::class,
   ];

... should be enough, right? Also, the authorizeResource method is NOT mentioned in the documentation.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire