Created
March 25, 2014 10:44
-
-
Save mikedugan/9759053 to your computer and use it in GitHub Desktop.
Validation with laravel and blade
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //use a service - don't forget to namespace! | |
| abstract class Validator { | |
| protected $errors; | |
| public function validate($input) | |
| { | |
| $validator = Validator::make($input, static::$rules); | |
| if($validator->fails()) | |
| { | |
| $this->errors = $validator->messages(); | |
| return false; | |
| } | |
| return true; | |
| } | |
| public function errors() | |
| { | |
| return $this->errors; | |
| } | |
| } | |
| class SomeValidator extends Validator { | |
| static $rules = [ ]; | |
| } | |
| //controller based | |
| use Path\To\Validation\SomeValidator as Validator; | |
| public function __construction(Validator $validator) | |
| { | |
| $this->validator = $validator; | |
| } | |
| public function someFunction() | |
| { | |
| $validator = \Validator::make(Input::all(), $rules); | |
| if($validator->fails()) return Redirect::back()->withErrors($validator)->withInput(); | |
| } | |
| //blade view | |
| <ul class="errors"> | |
| @foreach($errors->all('<li>:message</li>') as $error) | |
| {{ $error }} | |
| @endforeach | |
| </ul> | |
| //other ways of echoing errors | |
| //inline | |
| {{ $errors->first('title', 'span class="error">:message</span>') }} | |
| {{ $errors->first('body', '....') }} //etc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment