Skip to content

Instantly share code, notes, and snippets.

@stidges
Created January 1, 2018 16:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stidges/84d212138293b0e2ab71ccebd4b79d1d to your computer and use it in GitHub Desktop.
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)
<?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