Ellrion
11/22/2015 - 9:01 PM

Laravel FromRequest with methods: prepare (for change and replace input) and sometimes (for add sometimes rules to validator)

Laravel FromRequest with methods: prepare (for change and replace input) and sometimes (for add sometimes rules to validator)

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

abstract class FormRequest extends BaseFormRequest
{
    protected $prepared;

    /**
     * Проверяет является ли метод методом создания по REST.
     *
     * @return bool
     */
    public function isMethodCreation()
    {
        return $this->isMethod('post');
    }

    /**
     * {@inheritdoc}
     */
    protected function prepareForValidation()
    {
        if ($this->prepared) {
            return;
        }

        $attributes = $this->input();

        if (method_exists($this, 'prepare')) {
            $attributes = $this->prepare($attributes);
        }

        $this->prepared = true;
        $this->replace($attributes);

        parent::prepareForValidation();
    }

    /**
     * {@inheritdoc}
     */
    protected function getValidatorInstance()
    {
        $validator =  parent::getValidatorInstance();

        if (method_exists($this, 'sometimes')) {
            $this->sometimes($validator);
        }

        return $validator;
    }
}