我正在使用表单请求类来验证传递给我的控制器的数据。
此外,我正在使用策略来确定是否允许当前用户show
/ update
/destroy
等有问题的对象。
如果我使用策略,这是否意味着我可以简单地使用:
public function authorize()
{
return true;
}
在我的请求课程中?或者我应该做两次检查/以不同的方式写它们?
如果有人能对此有所了解,那就太好了。
谢谢。
请参阅 \Illuminate\Validation\ValidatesWhenResolvedTrait
<?php
namespace Illuminate\Validation;
use Illuminate\Contracts\Validation\ValidationException;
use Illuminate\Contracts\Validation\UnauthorizedException;
/**
* Provides default implementation of ValidatesWhenResolved contract.
*/
trait ValidatesWhenResolvedTrait
{
/**
* Validate the class instance.
*
* @return void
*/
public function validate()
{
$instance = $this->getValidatorInstance();
if (! $this->passesAuthorization()) {
$this->failedAuthorization();
} elseif (! $instance->passes()) {
$this->failedValidation($instance);
}
}
/**
* Get the validator instance for the request.
*
* @return \Illuminate\Validation\Validator
*/
protected function getValidatorInstance()
{
return $this->validator();
}
/**
* Handle a failed validation attempt.
*
* @param \Illuminate\Validation\Validator $validator
* @return mixed
*/
protected function failedValidation(Validator $validator)
{
throw new ValidationException($validator);
}
/**
* Determine if the request passes the authorization check.
*
* @return bool
*/
protected function passesAuthorization()
{
if (method_exists($this, 'authorize')) {
return $this->authorize();
}
return true;
}
/**
* Handle a failed authorization attempt.
*
* @return mixed
*/
protected function failedAuthorization()
{
throw new UnauthorizedException;
}
}
和 \Illuminate\Foundation\Http\FormRequest
/**
* Determine if the request passes the authorization check.
*
* @return bool
*/
protected function passesAuthorization()
{
if (method_exists($this, 'authorize')) {
return $this->container->call([$this, 'authorize']);
}
return false;
}
它只检查返回的结果,并在请求解决时确定是否继续。它没有通过策略或任何中间件或某事。那样奇怪。