表单验证
- 对于请求参数进行验证
- 官方文档:https://learnku.com/docs/laravel/12.x/validation/16955
生成验证规则
bash
php artisan make:request CaptchaRequest- 会生成
app/Http/Requests/CaptchaRequest.php文件
php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CaptchaRequest extends FormRequest
{
/**
* 表示是否开启验证
*/
public function authorize(): bool
{
return true;
}
/**
* 验证规则
*/
public function rules(): array
{
return [
'key' => ['required', 'string'],
'biz' => ['required'],
];
}
/**
* 验证错误消息
*/
public function messages(): array
{
return [
'key.required' => '请填写唯一标识',
'biz.required' => '请填写业务类型',
];
}
}使用
php
use App\Admin\Requests\CaptchaRequest;
/**
* 获取点选验证码
*/
public function create(CaptchaRequest $request): JsonResponse
{
// 依赖注入后自动验证
// ...
// 验证通过后,获取验证后的数据
$validated = $request->validated();
return $this->success(
$this->captcha->get($validated['key'], (string)($validated['biz'] ?? ''))
);
}