Laravel 提供了多种不同的方法来验证传入应用程序的数据。
- 在控制器中编写验证器逻辑;
- 使用 validate 手动创建验证器;
- 使用验证层创建表单请求验证(推荐);
<?php
namespace App\Http\Requests\Api;
use Illuminate\Foundation\Http\FormRequest;
class StorePositionRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|max:255',
'body' => 'required'
];
}
/**
* Get custom messages for validator errors.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'A title is required',
'title.max' => 'The title may not be greater than 255',
'body.required' => 'A message is required'
];
}
}