我正在建立一个API,其中一个数据库表Person
有52列,其中大多数都是必须的,我不会认为我做的方式是对的
public function store() {
if (! input::get('name') or ! input::get('age') or ! input::get('phone') or ! input::get('address') and so on till the 52 field) {
return "Unprocessable Entity";
}
return "Validated";
}
如何正确验证所有必填字段
谢谢
答案 0 :(得分:2)
您只需在请求文件中编写验证规则和消息,就可以直接在store
函数中调用,如
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Rule;
/**
* Class YourFileRequest
* @package App\Http\Requests
*/
class YourFileRequest extends Request
{
/**
* 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|unique:posts|max:255',
'body' => 'required',
];
}
/**
* Get the custom validation messages that apply to the request.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'Please enter title',
'title.max' => 'Please enter max value upto 255',
'body.required' => 'Please enter body',
];
}
}
在您的控制器中
use App\Http\Requests\YourFileRequest;
......
public function store(YourFileRequest $request)
{
//Your storing logic
}
答案 1 :(得分:1)
您可以通过两种方式实现:
第一个是
$this->validate($request,['email'=>'required|email|unique']);
其次,您可以使用以下命令创建单独的ValidationRequest:
php artisan make:request StoreRequest