传递 class 名称以查看控制器索引方法 returns 上的策略错误,传递的参数太少

Passing class name to view policy on controller index method returns error that too few arguments were passed

我正在尝试为我的控制器的索引方法测试策略。我正在将 class 名称传递给授权助手,但我收到了 500 状态和一个错误

1) Tests\Feature\FunderFeatureTest::an_admin_should_be_able_to_view_a_list_of_funders Symfony\Component\Debug\Exception\FatalThrowableError: Too few arguments to function App\Policies\FunderPolicy::view(), 1 passed in /home/vagrant/code/rtl/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 614 and exactly 2 expected

我做错了什么?所有其他策略都有效(包括不需要模型的 create() 和 store() 方法)。我意识到这与 SO 上的许多其他问题类似,但是大多数似乎是由于人们没有将 class 名称传递给授权方法或问题发生在不同的控制器方法(例如作为更新())。如果之前有人问过这个具体问题,我深表歉意,我已经断断续续地研究了两周,但找不到我正在寻找的答案。

FundersController.php

namespace App\Http\Controllers;

use App\Funder;
use Illuminate\Http\Request;

class FundersController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $this->authorize('view', Funder::class);

        return view('funders.index', [
            'funders' => Funder::all(),
        ]);
    }
}

FunderPolicy.php

namespace App\Policies;

use App\User;
use App\Funder;
use Illuminate\Auth\Access\HandlesAuthorization;

class FunderPolicy
{
    use HandlesAuthorization;
    public function view(User $user, Funder $funder)
    {
        return ($user->isAdmin() || $user->isSuperAdmin());
    }
}

FunderFeatureTest.php(供参考)

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class FunderFeatureTest extends TestCase
{
    use RefreshDatabase;
    /** @test */
    public function an_admin_should_be_able_to_view_a_list_of_funders()
    {
        $this->withoutExceptionHandling();
        $this->signIn('admin');

        $this->get('/funders')
            ->assertOk();
    }

    /** @test */
     public function a_user_should_not_be_able_to_view_a_list_of_funders()
    {
        $this->signIn();

        $this->get('/funders')
            ->assertStatus(403);
    }
}

我不确定这是否是让它工作的合适方法,但传递 Funder 模型的新实例而不是 class 名称似乎可以解决问题。

$this->authorize('view', Funder::class); 更改为 $this->authorize('view', new \App\Funder());