我正在Laravel中构建一个具有资源控制器的自定义程序包。对于此示例,资源为Organization
。在此控制器中,定义了基本的index
,show
,store
等操作。
这是我在控制器中的store
方法:
/**
* Store a newly created Organization in storage.
*
* @param OrganizationStoreRequest $request
* @return JsonResponse
*/
public function store($request): JsonResponse
{
$newOrganization = new Organization($request->all());
if ($newOrganization->save()) {
return response()->json($newOrganization, 201);
}
return response()->json([
'message' => trans('organilations::organisation.store.error')
], 500);
}
我的OrganzationStoreRequest
目前非常基本:
class OrganizationStoreRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => 'required'
];
}
}
在Laravel应用程序中使用包时,可以在API上调用store方法。我在这里的问题是,我想让我的软件包用户能够使用自己的请求覆盖OrganizationStoreRequest
,因为他们可能不得不使用不同的授权或验证方法。
我尝试构建中间件并将自己的实例绑定到OrganizationStoreRequests
,但是没有得到想要的结果。
该包的用户是否可以覆盖我的包控制器中的OrganizationStoreRequets
?
答案 0 :(得分:0)
在Larachat的开发人员的帮助下,我们得出了以下(简单的)解决方案。
在创建自己的请求时,我们可以将其实例绑定到IoC容器。例如,创建OrganizationOverrideRule
并扩展原始文件:
class OrganizationOverrideRules extends OrganizationStoreRequest
{
public function rules(): array
{
return [
'name' => 'required',
'website' => 'required',
'tradename' => 'required'
];
}
}
然后在AppServiceProvider
中可以像这样绑定新实例:
App::bind(
OrganizationStoreRequest::class,
OrganizationOverrideRules::class
);
然后OrganizationOverrideRules
将用于验证和授权。