다음은 원하는 것을 달성하기 위해 따라야 할 단계입니다.
1) 일반적으로, 나는 장인이 만들 수 있습니다 당신은 수동으로 다음 정책을 등록 할 경우,
php artisan make:policy -m=Model
그러나 다음 명령을 실행하여 나를 위해 정책 개체를 등록 할 것입니다, 당신은 그들을지도 할 필요가 당신의 AuthServiceProvider. 예 :
protected $policies = [
'App\Post' => 'App\Policies\PostPolicy',
];
2) 모델 정책에 이미 로직이 있습니다.
3) 컨트롤러의 editPost 액션에서 무엇보다 먼저 게시물을 볼 수있는 권한을 부여 할 수 있습니다. 예 :
$this->authorize('view', $post);
4) 블레이드에서 @can 및 @endcan 블록에 액세스 할 수도 있습니다.
사용자 이름이나 사용자 ID 질문이가는 한 전체 사용자 개체에 액세스 할 수 있으므로 사용자가 속성을 사용하여 체크를 실행할 수 있습니다.
희망이 있습니다. 여기
는
/**
* Determine if the given ability should be granted for the current user.
*
* @param string $ability
* @param array|mixed $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorize($ability, $arguments = [])
{
$result = $this->raw($ability, $arguments);
if ($result instanceof Response) {
return $result;
}
return $result ? $this->allow() : $this->deny();
}
가 여기 내 PostController에서
https://laravel.com/docs/5.5/authorization#creating-policies https://laravel.com/docs/5.5/authorization#authorizing-actions-using-policies
$ this-> authorize ('view', $ post); 당신이 쓴 것처럼, 그것은 사용자 변수가 필요하지 않습니다? 내가 필터링해야하기 때문에 게시물이이 사용자에게 속한 것입니다. – Ying
사용자 모델을 정책 모델에 매핑하면 정책에서 사용자를 이미 얻었고 게시물의 경우 사용자가 해당 게시물을 전달하게됩니다. 공개 기능보기 (User $ user, Post $ post) { return $ user-> id === $ post-> user_id || $ user-> hasRole ('admin'); } – alithedeveloper