Instantly share code, notes, and snippets.

Embed
What would you like to do?
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