如何在 Laravel 5.2 中定义一个没有参数的策略方法?
How to define a policy method with no argument in Laravel 5.2?
有时需要检查用户对不带参数的操作的授权,例如 create/store 方法:
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine if the user can create a new post.
*
* @param \App\User $user
* @return bool
*/
public function create(User $user)
{
if($user->is_admin)
{
return true;
}
return false;
}
}
并在 PostController 中使用授权方法:
class PostController extends Controller
{
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create');
//...
}
}
但是好像没有参数的policy方法不能对应controller上的authorize方法,授权总是失败
如果定义的策略方法没有像这样的参数:
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine if the user can create a new post.
*
* @param \App\User $user
* @return bool
*/
public function create(User $user)
{
return $user->is_admin;
}
}
您可以使用这样的授权方式:
class PostController extends Controller
{
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create', \App\Post::class);
//...
}
}
并在 blade 模板中使用 @can
Blade 指令:
@can('create', \App\Post::class)
<!-- The Current User Can Update The Post -->
@endcan
也可以使用 Gate
门面、User
模型或 policy
助手。
有时需要检查用户对不带参数的操作的授权,例如 create/store 方法:
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine if the user can create a new post.
*
* @param \App\User $user
* @return bool
*/
public function create(User $user)
{
if($user->is_admin)
{
return true;
}
return false;
}
}
并在 PostController 中使用授权方法:
class PostController extends Controller
{
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create');
//...
}
}
但是好像没有参数的policy方法不能对应controller上的authorize方法,授权总是失败
如果定义的策略方法没有像这样的参数:
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine if the user can create a new post.
*
* @param \App\User $user
* @return bool
*/
public function create(User $user)
{
return $user->is_admin;
}
}
您可以使用这样的授权方式:
class PostController extends Controller
{
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create', \App\Post::class);
//...
}
}
并在 blade 模板中使用 @can
Blade 指令:
@can('create', \App\Post::class)
<!-- The Current User Can Update The Post -->
@endcan
也可以使用 Gate
门面、User
模型或 policy
助手。