Reputation: 2243
I'm creating my first Laravel policy. I have a basically fresh laravel 5.4 project that has a Project model. I've created one policy named ProjectPolicy but I'm having trouble getting all of the methods to work.
If I call $user->can('create', Project::class)
I get the 'here' dump and it returns true. However the view, create, and delete actions never reach the ProjectPolicy. "here" is never dumped and false is always returned. I can't think of or find any reason why one policy method would work while the others do not. What am I missing?
App\Policies\ProjectPolicy.php
namespace App\Policies;
use App\User;
use App\Project;
use Illuminate\Auth\Access\HandlesAuthorization;
class ProjectPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user has a specific ability for projects.
*
* @param \App\User $user
* @param \App\Project $project
* @return mixed
*/
public function before($user, $ability)
{
var_dump('here');
}
/**
* Determine whether the user can view the project.
*
* @param \App\User $user
* @param \App\Project $project
* @return mixed
*/
public function view(User $user, Project $project)
{
return true;
}
/**
* Determine whether the user can create projects.
*
* @param \App\User $user
* @return mixed
*/
public function create(User $user)
{
return true;
}
/**
* Determine whether the user can update the project.
*
* @param \App\User $user
* @param \App\Project $project
* @return mixed
*/
public function update(User $user, Project $project)
{
return true;
}
/**
* Determine whether the user can delete the project.
*
* @param \App\User $user
* @param \App\Project $project
* @return mixed
*/
public function delete(User $user, Project $project)
{
return true;
}
}
AuthServiceProvider.php
namespace App\Providers;
use App\Project;
use App\Policies\ProjectPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Project::class => ProjectPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
Upvotes: 2
Views: 1910
Reputation: 987
The problem is likely that you are calling $user->can('view', Project::class)
without passing an instance of the project. Try calling $user->can('view', $project)
where $project is an instance of the project class for all those methods which require a project in their function definition.
Upvotes: 3