api - 无法将请求传递给策略,因此我可以验证一些问题
问题描述
我授权这样的商店
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"
当我在控制器中添加请求时它可以,但是当我在策略上添加它时它返回一个空用户对象!!!这是为什么?
解决方案
你犯了一些错误,错过了一些东西。
据我所知,您有一些公司,每个公司Company
都有一些JobPost
s。
首先,您不应该在职位发布请求的正文中传递您的公司 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请完全复制并粘贴所有依赖项的类,并花更多时间来完善您的帖子。如果这很难写出你的问题,那就很难阅读、理解和正确回答。
推荐阅读
- rx-java - 如何使用带有 EmbeddedChannel 的 rxNetty 客户端进行测试
- php - 使用 Laravel 在服务器上上传图片
- python - 如何从 softmax 层提取权重?
- javascript - 如何在存储在数组中的 html vue js 中提供编辑功能?
- python - 使用 Pandas 计算 Python 中每组列的一些值
- wordpress - Wordpress 单一安装在子目录站点地图重写规则 Nginx
- typescript - 泛型和映射类型缩小
- xml - XSD:独特的元素
- java - 使用 BouncyCastle 接受过期的 CRL
- .net - 缓存从 ASP.NET 核心 Web api 中的大量文件中读取的内容