我正在使用laravel,并从客户端输入json。我想知道是否有办法创建一个表单请求,而不是url参数。我在网上找到了这门课:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class JsonRequest extends FormRequest {
/**
* Get the validator instance for the request.
*
* @return \Illuminate\Validation\Validator
*/
protected function getValidatorInstance()
{
$factory = $this->container->make('Illuminate\Validation\Factory');
if (method_exists($this, 'validator'))
{
return $this->container->call([$this, 'validator'], compact('factory'));
}
return $factory->make(
$this->json()->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes()
);
}
}
现在,当我创建一个扩展此而不是Request的类时,我能够验证。这是一个例子:
<?php
namespace App\Http\Requests;
use App\Http\Middleware\AuthTokenMiddleware;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Input;
class VotesCreateRequest extends JsonRequest
{
public function response(array $errors)
{
//
return response()->json(["error_list" => $errors], 200);
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{return true;
if(AuthTokenMiddleware::getUser()->can('access-group',Input::get("grp_id"))){
return true;
}
else{
return false;
}
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'sub_items'=>'required|array',
'sub_items.*.email' =>'required'
];
}
}
但我想知道如何验证json文件中项目的内容。
例如,我有: {“sub_items”:[“某事”,“另一件事”,“又一件事”,“另一件事”,“最后一件”]}
如何验证子sub_items中的所有这些项目是否为电子邮件类型?