在Laravel 中,許多建立和編輯的的介面都是需要做資料驗證的,對於資料驗證一般有2種方方式
在控制器裡直接使用Request的validate方法
類,該類別整合自
Http\Request如果使用第一種方法,會比較亂,看起來不夠優雅但是如果使用第二種方式,那麼針對每一種請求都要定義一個FormRequest例如:
ArticleStoreRequest和
ArticleUpdateRequest但是你會發現基本上驗證規則是一樣的,當然你可以在控制器方法裡只注入一個Request,但如果針對於一個Model 有多個Update的那種,例如使用者模組,修改密碼/修改暱稱/修改頭像/修改位址/修改。 。 。怎麼處理呢所以這幾天針對這種情況,改進了下Laravel的Request機制,加了一個場景驗證
第一步:先建立一個AbstractRequest
的基底類別<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Str; /** * 使用方法: * Class AbstractRequest * @package App\Http\Requests */ class AbstractRequest extends FormRequest { public $scenes = []; public $currentScene; //当前场景 public $autoValidate = false; //是否注入之后自动验证 public $extendRules; public function authorize() { return true; } /** * 设置场景 * @param $scene * @return $this */ public function scene($scene) { $this->currentScene = $scene; return $this; } /** * 使用扩展rule * @param string $name * @return AbstractRequest */ public function with($name = '') { if (is_array($name)) { $this->extendRules = array_merge($this->extendRules[], array_map(function ($v) { return Str::camel($v); }, $name)); } else if (is_string($name)) { $this->extendRules[] = Str::camel($name); } return $this; } /** * 覆盖自动验证方法 */ public function validateResolved() { if ($this->autoValidate) { $this->handleValidate(); } } /** * 验证方法 * @param string $scene * @throws \Illuminate\Auth\Access\AuthorizationException * @throws \Illuminate\Validation\ValidationException */ public function validate($scene = '') { if ($scene) { $this->currentScene = $scene; } $this->handleValidate(); } /** * 根据场景获取规则 * @return array|mixed */ public function getRules() { $rules = $this->container->call([$this, 'rules']); $newRules = []; if ($this->extendRules) { $extendRules = array_reverse($this->extendRules); foreach ($extendRules as $extendRule) { if (method_exists($this, "{$extendRule}Rules")) { //合并场景规则 $rules = array_merge($rules, $this->container->call( [$this, "{$extendRule}Rules"] )); } } } if ($this->currentScene && isset($this->scenes[$this->currentScene])) { $sceneFields = is_array($this->scenes[$this->currentScene]) ? $this->scenes[$this->currentScene] : explode(',', $this->scenes[$this->currentScene]); foreach ($sceneFields as $field) { if (array_key_exists($field, $rules)) { $newRules[$field] = $rules[$field]; } } return $newRules; } return $rules; } /** * 覆盖设置 自定义验证器 * @param $factory * @return mixed */ public function validator($factory) { return $factory->make( $this->validationData(), $this->getRules(), $this->messages(), $this->attributes() ); } /** * 最终验证方法 * @throws \Illuminate\Auth\Access\AuthorizationException * @throws \Illuminate\Validation\ValidationException */ protected function handleValidate() { if (!$this->passesAuthorization()) { $this->failedAuthorization(); } $instance = $this->getValidatorInstance(); if ($instance->fails()) { $this->failedValidation($instance); } } }
<?php namespace App\Http\Requests; class UserRequest extends AbstractRequest { public $scenes = [ 'nickname' => 'nickname', 'avatar' => 'avatar', 'password' => 'password', 'address' => 'province_id,city_id' ]; public function rules() { return [ //全部的验证规则 'mobile' => [], 'nickname' => [], 'password' => [ 'required', 'min:6', 'max:16' ], 'avatar' => [], 'province_id' => [], 'city_id' => [], //... ]; } public function passwordRules() { return [ 'password' => [ 'required', 'min:6', 'max:16', 'different:$old_password' //修改新密码不和旧密码相同,此处只是举例子,因为密码需要Hash处理才能判断是否相同 ] ]; } }控制器方法UserController
<?php namespace App\Http\Controllers; use App\Http\Requests\UserRequest; class UserController { public function register(UserRequest $request) { $request->validate(); //默认不设置场景 全部验证 //... } public function updateAddress($id, UserRequest $request) { $request->scene('address')->validate(); //... } public function updateAvatar($id, UserRequest $request) { $request->validate('avatar'); //... } public function updatePassword($id, UserRequest $request) { //设置password场景,只验证password字段,并且使用新的password规则替换原来的password规则 $request->scene('password') ->with('password') ->validate(); //... } }
同時還有我也修改了ORM的場景驗證規則,可以在model裡設定經常,同時滿足多場景建立和更新
以上是教你修改Laravel FormRequest驗證,實作場景驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!