Skip to content

Instantly share code, notes, and snippets.

@caiotava
Created May 3, 2015 05:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caiotava/b73fe9496f9a65a07611 to your computer and use it in GitHub Desktop.
Save caiotava/b73fe9496f9a65a07611 to your computer and use it in GitHub Desktop.
Custom FormRequest Laravel

CustomRequest

Abstract class to allow custom validation

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Http\Exception\HttpResponseException;

abstract class CustomRequest extends Request
{
    /**
     * Custom Validation without validation of Laravel.
     *
     * @return boolean
     */
    abstract public function customValidate();

    /**
     * Return the errors.
     *
     * @return array
     */
    abstract public function getErrorMessages();

    /**
     * Validate the class instance.
     *
     * @return void
     */
    public function validate()
	{
        if (!$this->passesAuthorization()) {
            $this->failedAuthorization();
        }
        elseif (!$this->customValidate()) {
            $this->throwExceptionValidation($this->getErrorMessages());
        }
    }

    protected function throwExceptionValidation(array $errors)
    {
        $response = $this->response($errors);

        throw new HttpResponseException($response);
    }
}

Test CustomFormRequest

namespace App\Http\Requests;

class TestRequest extends CustomRequest
{
	protected $redirect = '/';

	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		return true;
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function customValidate()
	{
		return false;
	}

	public function getErrorMessages()
	{
		return [
			'title' => 'Title is required',
		];
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment