【问题标题】:I have problem with laravel policies..it doesn't work我对 laravel 政策有疑问..它不起作用
【发布时间】:2021-05-31 15:39:16
【问题描述】:

这是我的 StorePolicy:

public function view(User $user, store $store)
{
   return true;
}

,这是我的 AuthServiceProvider:

protected $policies = [
   store::class => StorePolicy::class,
];

,这是我的 api.php 文件:

Route::group([ 'middleware' => ['auth:sanctum']],function () {
    Route::resources([
       'store' => StoreController::class,
    ]);
});

这是我的控制器:

public function __construct()
{
   $this->authorizeResource(store::class, 'store');
}

public function show($id)
{
   echo 'hi :)';
}

这是我的问题,当我检查路线('/store')时得到结果,但是当我检查路线('/store/1',.eg)时,我得到 403 错误。我应该怎么办 ? :(

这很奇怪,在我的控制器的索引方法中,当我检查下面的代码时,我得到了我想要的正确结果并且它是否有效。

public function index()
{
   $store = new store();
   $this->authorize('view', $store);
        
   $data = store::orderBy('created_at', 'desc')->simplePaginate(10);
   return response([
      'data' => $data,
   ], 200);
}

【问题讨论】:

标签: php laravel


【解决方案1】:

试试

public function index(store $store)
{

代替

public function index()
{
   $store = new store();

【讨论】:

  • 谢谢,但我的问题是索引以外的其他方法。我经常收到 403 错误。
  • 确保您将 store 的实例作为第二个参数传递给授权,而不是集合或数组或其他任何东西。它应该与策略方法签名匹配。
  • 我将 store 的实例作为第二个参数添加到方法 show "show($id, store $store)",但我收到错误 Too little arguments to function App\\Http\\Controllers\ \StoreController::show()。我该怎么办?
  • 这意味着在控制器中它现在要求第二个参数:$this->authorize('show', $store);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 2021-06-05
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多