Skip to content

Instantly share code, notes, and snippets.

@nmsmith22389
Last active April 1, 2019 22:30
Show Gist options
  • Save nmsmith22389/a9e92c2dbd5b28551b282c8095c767df to your computer and use it in GitHub Desktop.
Save nmsmith22389/a9e92c2dbd5b28551b282c8095c767df to your computer and use it in GitHub Desktop.
Laravel - Form Request Example
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* Laravel Transformer
*
* Package at:
* https://github.com/konsulting/laravel-transformer
*/
use Konsulting\Laravel\Transformer\TransformingRequest;
class ExampleFormRequest extends FormRequest
{
/**
* Add this trait to transform the input values before validating.
*/
use TransformingRequest;
/**
**************************************************
* Optional Properties
* (only include if you need)
**************************************************
*/
/**
* The URI to redirect to if validation fails.
*
* @var string
*/
protected $redirect;
/**
* The route to redirect to if validation fails.
*
* @var string
*/
protected $redirectRoute;
/**
* The controller action to redirect to if validation fails.
*
* @var string
*/
protected $redirectAction;
/**
* The key to be used for the view error bag.
*
* @var string
*/
protected $errorBag = 'default';
/**
* The input keys that should not be flashed on redirect.
*
* @var array
*/
protected $dontFlash = ['password', 'password_confirmation'];
/**
* 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.
*
* > You may type-hint any dependencies you need within the rules method's signature.
* > They will automatically be resolved via the Laravel service container.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
/**
* Set custom messages for validator errors.
*
* @return array
*/
public function messages()
{
return [];
}
/**
* Set custom attributes for validator errors.
*
* @return array
*/
public function attributes()
{
return [];
}
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
/**
* Returns an array of filters to apply to incoming form input.
*
* @return array
*/
public function transformRules()
{
return [
'name' => 'trim|uppercase',
'message' => 'trim',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment