Skip to content

Instantly share code, notes, and snippets.

@martinbean
Last active August 29, 2015 14:05
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 martinbean/31fdafe13d1faa6e5634 to your computer and use it in GitHub Desktop.
Save martinbean/31fdafe13d1faa6e5634 to your computer and use it in GitHub Desktop.
Laravel validation trait.
<?php
trait ValidatorTrait {
protected $validator;
public function isValid()
{
return $this->getValidator()->passes();
}
public function getValidator()
{
return Validator::make($this->attributes, $this->rules);
}
public function getErrors()
{
return $this->getValidator()->errors();
}
}
@martinbean
Copy link
Author

Usage:

Import the trait, and then define a $rules property in your model class with the validation rules.

<?php

class Article extends \Eloquent {

    use ValidatorTrait;

    protected $rules = array(
        'headline' => 'required'
    );

}

And then use as thus:

<?php

class ArticleController extends \BaseController {

    public function store()
    {
        $article = new Article;
        $article->headline = Input::get('headline');

        if ($article->isValid())
        {
            $article->save();

            return Redirect::route('article.index')
                ->withSuccess(Lang::get('messages.article_saved');
        }
        else
        {
            return Redirect::route('article.create')
                ->withErrors($article->getErrors())
                ->withInput();
        }
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment