首页 > 解决方案 > 无法将请求传递给策略,因此我可以验证一些问题

问题描述

我授权这样的商店

    public function store( Request $request)
{
    $this->authorizeApi('store',JobPost::class, $request);
    return $this->jobPostRepository->store($request);
}

在政策中我的商店方法看起来像这样

    public function store(Request $request)
{
    $user=auth()->user();
    return ($user->company_id == $request->company_id)
        &&($request->expiration_date->isAfter($request->publish_date))
        &&($request->publish_date->isAfter(now()))
        ;
}

当我运行它时,我得到

"Argument 1 passed to App\Policies\JobPostPolicy::store() must be an instance of Illuminate\Http\Request, instance of App\Models\User given, called in C:\xampp\htdocs\balatar1\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 481"

当我在控制器中添加请求时它可以,但是当我在策略上添加它时它返回一个空用户对象!!!这是为什么?

标签: apirequestauthorizationlaravel-5.6policy

解决方案


你犯了一些错误,错过了一些东西。

据我所知,您有一些公司,每个公司Company都有一些JobPosts。

首先,您不应该在职位发布请求的正文中传递您的公司 ID,您的商店路线应该是这样的,https://example.com/company/{company_id}/job-post然后您就可以通过 Laravel 模型绑定来捕获公司模型!

所以你的路线应该定义为:

Route::group(['prefix' => 'company', 'as' => 'company.'], function () {
    Route::group(['prefix' => '{company}'], function () {
        Route::resource('job-post', 'JobPostController', ['parameters' => ['job-post' => 'jobPost']);
    });
    Route::resource('', 'ComapnyController', ['parameters' => ['' => 'company']);
}

你的控制器看起来像(我将JobPostRequest在答案的第二部分解释):

class JobPostController extends Controller
{
    public function store(JobPostRequest $request, Company $company)
    {
        $this->authorizeApi('store', [JobPost::class, $company]);

        // the rest...
    }
}

其次,您需要一个 Request 类来为您进行验证。

根据文档首先你必须创建一个Request类,然后它需要运行php artisan make:request JobPostRequest

那么你的职位发布请求应该是这样的:

class BaseRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|max:255',
            'body' => 'required|max:65535',
        ];
    }
}

您也可以在上面的类方法中执行您在策略中所做的事情,authorize但不建议这样做。

第三,在您的策略 ( JobPostPloicy) 中,您必须检查当前登录的用户是否能够发布给定的工作$company

PS请完全复制并粘贴所有依赖项的类,并花更多时间来完善您的帖子。如果这很难写出你的问题,那就很难阅读、理解和正确回答。


推荐阅读