3
3

More than 5 years have passed since last update.

laravel4 validateのattributeの設定

Last updated at Posted at 2014-09-29

エラーメッセージの:attributeに日本語を設定する

ex)http://stackoverflow.com/questions/17047116/laravel-validation-attributes-nice-names

カスタムvalidateの設定
http://qiita.com/MasatoYoshioka@github/items/64784c986e9e54b0d404

CustomValidator.php
    /* validate カスタムattributeの設定
    *
    */
    public function setAttributeNames(array $attributes)
    {
        $this->customAttributes = $attributes;
        return $this;
    }

Model.php

class Model extends Eloquent
{
    protected $table   = 'models';
    protected $guarded = array( 'id' );

    public static $validate_attributes = [
        'name' => '名前',
    ];

    public static function validateCreate( $input )
    {
        $rules = [
            'name' => 'required',
        ];
        $validator = Validator::make( $input, $rules );
        return $validator->setAttributeNames( self::$validate_attributes );
    }
}

Controller.php

    public function store()
    {
        try{
            $input     = Input::all();
            $validator = Model::validateCreate( $input );
            if( $validator->fails() ){
                return Redirect::back()
                        ->withErrors( $validator );
            }
       //ここに成功時の処理
        }catch( Exception $e ){
            return Redirect::back()
                    ->with( 'error_message', 'errorです' );
        }
    }
View.php
<div class="form-group">
    <label class="col-sm-3 control-label">名前</label>
    <div class="col-sm-9">
{{ Form::text( 'name' ,null, [ 'class' => 'form-control' ]) }}
{{ $errors->first( 'name') }}
    </div>
</div>
<p class="text-center"><button type="submit" class="btn btn-primary" rule="button">購入</button></p>

名前を未入力でエラーを出すと
「名前は必須です。」
と表示される。

OK

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3