Created
January 1, 2018 16:33
-
-
Save stidges/84d212138293b0e2ab71ccebd4b79d1d to your computer and use it in GitHub Desktop.
Code to accompany the 'Reusable Validation Rules with Laravel Form Requests' post (https://stidges.com/reusable-validation-rules-with-laravel-form-requests)
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 characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment