Laravel政策永远是错误的 [英] Laravel policy always false
问题描述
我正试图允许用户在Laravel 5.4中查看自己的个人资料.
I'm trying to allow user to view their own profile in Laravel 5.4.
UserPolicy.php
public function view(User $authUser, $user)
{
return true;
}
在AuthServiceProvider.php中注册的策略
protected $policies = [
App\Task::class => App\Policies\TaskPolicy::class,
App\User::class => App\Policies\UserPolicy::class
];
路线
Route::group(['middleware' => 'auth'], function() {
Route::resource('user', 'UserController');
} );
刀片模板
@can ( 'view', $user )
// yes
@else
// no
@endcan
UserController.php
public function profile()
{
return $this->show(Auth::user()->id);
}
public function show($id)
{
$user = User::find($id);
return view('user.show', array( 'user'=>$user,'data'=>$this->data ) );
}
返回始终为"false".与从控制器调用策略相同.我哪里出问题了?
The return is always 'false'. Same for calling policy form the controller. Where do I go wrong?
推荐答案
回答我自己的问题感觉很奇怪,但是当我遇到没有后续问题的问题时,我讨厌它.
Answering my own question feels weird, but I hate it when I come across questions without followups.
So after double checking It turned out that if I remove authorizeResource from the constructor:
public function __construct()
{
$this->authorizeResource(User::class);
}
并在控制器功能中检查授权:
and check for authorization in the controller function:
$this->authorize('view',$user);
一切正常.
在策略函数中添加$user
作为参数时,我一定错过了这一部分.因此,永远不会在authorizeResource
方法中传递要查看的用户.
everything works.
I must've missed this part when I added $user
as a parameter in the policy function. So the user to be viewed is never passed in the authorizeResource
method.
感谢大家抽出宝贵的时间来帮助我.
Thanks everyone for taking your time to help me.
这篇关于Laravel政策永远是错误的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!