Skip to content

Instantly share code, notes, and snippets.

@stidges
Created January 1, 2018 16:33
Show Gist options
  • Select an option

  • Save stidges/84d212138293b0e2ab71ccebd4b79d1d to your computer and use it in GitHub Desktop.

Select an option

Save stidges/84d212138293b0e2ab71ccebd4b79d1d to your computer and use it in GitHub Desktop.

Revisions

  1. stidges created this gist Jan 1, 2018.
    53 changes: 53 additions & 0 deletions Request.php
    Original 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;
    }
    }