chhw/form-request
此包可以使用表单请求,就像Laravel一样。
1.0.4
2021-11-17 15:59 UTC
Requires
- php: >=7.2
- laravel/lumen-framework: >=7.0
README
此包可以使用表单请求,就像Laravel一样。
安装
通过composer安装
$ composer require chhw/form-request
在 bootstrap/app.php
中,你应该
- 取消注释
$app->withFacades();
- 添加
$app->register(CHHW\FormRequest\FormRequestServiceProvider::class);
用法
就像使用Laravel一样!
通过结构化文件
添加一些请求,例如:app/Http/Requests/CreatePost.php
,继承 CHHW\FormRequest\FormRequest
app/Http/Requests/CreatePost.php
<?php namespace App\Http\Requests; use CHHW\FormRequest\FormRequest; class CreatePost extends FormRequest { /** * 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|string", ]; } public function withValidator($validator) { $validator->after(function ($validator) { if (true) { $validator->errors()->add('field', 'Something is wrong with this field!'); } }); } }
app/Http/Controllers/ExampleController.php
use App\Http\Requests\CreatePost; class ExampleController extends Controller { public function test(CreatePost $request) { dd($request->all()); // ... } }
或者在控制器中
app/Http/Controllers/ExampleController.php
use App\Rules\Uppercase; use Illuminate\Http\Request; class ExampleController extends Controller { public function create(Request $request) { $request->validate(["author" => ["required", new Uppercase],]); // ... } }
app/Rules/Uppercase.php
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class Uppercase implements Rule { /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return strtoupper($value) === $value; } /** * Get the validation error message. * * @return string */ public function message() { return 'The :attribute must be uppercase.'; } }
通过命令获取请求和规则文件
php artisan make:request CreatePost php artisan make:rule Uppercase
自定义本地化错误消息
就像laravel一样!
添加 resources/lang/en/validation.php
,以及其他国家语言。
错误处理器
app/Exceptions/Handler.php
public function render($request, Throwable $exception) { if($exception instanceof ValidationException){ return response()->json(["message" => $exception->getMessage(), "details" => $exception->errors()]); } return parent::render($request, $exception); }