Created
January 1, 2018 16:33
-
-
Save stidges/84d212138293b0e2ab71ccebd4b79d1d to your computer and use it in GitHub Desktop.
Revisions
-
stidges created this gist
Jan 1, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Validator; abstract class Request extends FormRequest { /** * Apply the trait rules to the validator. * * @param \Illuminate\Validation\Validator $validator * @return void */ public function withValidator(Validator $validator) { if ($rules = $this->getTraitRules()) { $validator->addRules($rules); } } /** * Get the rules from the used traits. * * @return array */ protected function getTraitRules() { return array_reduce(class_uses(static::class), function ($rules, $trait) { $rulesMethod = $this->makeRulesMethodName($trait); if (! is_null($rulesMethod) && method_exists($this, $rulesMethod)) { $rules = array_merge($rules, $this->{$rulesMethod}()); } return $rules; }, []); } /** * Make the rules method name based on the given trait name, if it matches the required format. * * @param string $trait * @return string */ protected function makeRulesMethodName($trait) { preg_match('/^Has([A-Za-z]+)Fields$/', class_basename($trait), $matches); return isset($matches[1]) ? camel_case($matches[1]).'Rules' : null; } }