我创建了我的第一个Laravel政策。我有一个基本上新鲜的laravel 5.4项目,它有一个Project模型。我创建了一个名为ProjectPolicy的策略,但是我无法使所有方法都能正常工作。
如果我致电$user->can('create', Project::class)
,我会在这里打电话给' dump并返回true。但是,视图,创建和删除操作永远不会到达ProjectPolicy。 "此处"永远不会被转储,总是返回false。我无法想到或找到任何理由,为什么一种政策方法可行,而其他政策方法则不然。我错过了什么?
应用\策略\ 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();
//
}
}
答案 0 :(得分:2)
问题可能是您在没有传递项目实例的情况下调用$user->can('view', Project::class)
。尝试调用$user->can('view', $project)
,其中$ project是项目类的一个实例,用于在函数定义中需要项目的所有方法。