Haf*_*ari 3 laravel laravel-5.2 laravel-authorization
有时需要检查用户对没有参数的操作的授权,如 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;
}
}
Run Code Online (Sandbox Code Playgroud)
并在 PostController 中使用授权方法:
class PostController extends Controller
{
/**
* Show the form for creating a new post.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$this->authorize('create');
//...
}
}
Run Code Online (Sandbox Code Playgroud)
但似乎没有参数的策略方法不能对应控制器上的授权方法,授权总是失败。
如果定义了一个没有参数的策略方法,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用授权方法:
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);
//...
}
}
Run Code Online (Sandbox Code Playgroud)
并在刀片模板中使用@canBlade 指令:
@can('create', \App\Post::class)
<!-- The Current User Can Update The Post -->
@endcan
Run Code Online (Sandbox Code Playgroud)
也可以使用Gate外观、User模型或policy助手。
| 归档时间: |
|
| 查看次数: |
2311 次 |
| 最近记录: |