9
9

More than 5 years have passed since last update.

Laravelでログイン画面②〜バリデーション

Last updated at Posted at 2014-01-13

前回の続きから。

まずは前回のViewのemailとpasswordのタグにnameが足りなかったので追加。


<input type="text" id="email" name="email" class="form-control" placeholder="email">


<input type="password" name="password" id="password" class="form-control" placeholder="password">

当たり前だけどnameがないとPOSTで値を取得できない。(これのせいで②時間くらい悩んでたなんて言えない)

次にroute.phpとLoginsController.phpを編集。laravelは4からCamelCaseが主流?になったらしいのでそれにならって関数名を変更するのと、POSTされてきた値を取得する関数を追加する

route.php

//最初はここに飛ぶ(名前をaction_indexからgetLoginに)
Route::get('login', 'LoginsController@getLogin');

//POSTされたときはこっち
Route::post('login', 'LoginsController@postLogin');

LoginsController.php

        //関数名をgetLoginに変更
        public function getLogin() {
                return View::make('logins.index');
        }

        //POSTされたときの関数を追加
        public function postLogin(){


        }       

とりあえずコントローラには関数を追加しておく。次にバリデーション用のモデルを作る

app/modelディレクトリ以下にLogin.phpを新規作成


vi app/model/Login.php

バリデーションを行うモデルを作成する

Login.php

class Login extends Eloquent
{
    protected $fillable = ['email', 'password'];
    protected $errors;

    public function validate(array $params)
    {
        $validator = Validator::make($params, [
            'email' => array('required','email'),
            'password'  => 'required',
        ]);

        if ($validator->passes()) {
            return true;
        } else {
            $this->errors = $validator->messages();
            return false;
        }
    }

    public function errors()
    {
        return $this->errors;
    }
}

ここで使用しているバリデートメソッドはLaravelの公式ページで紹介されている
http://laravel4.kore1server.com/docs/validation#rule-email

また、モデル自体はこちらのサイトを参考にさせていただいた
http://atijusts.hatenablog.com/entry/2013/11/05/023755

モデルができたら、コントローラで呼び出してみる。コンストラクタで呼び出すことで、後からモデル自体を変更できるらすい。(依存性の注入。。。だよね?)

LoginsController.php

Class LoginsController extends BaseController{

        //プロパティを追加
        protected $login;

        public function __construct(Login $login)
        {
                //プロパティに先ほど作成したバリデーションモデルのインスタンスをセット
                $this->login = $login;
        }

        public function getLogin() {
                return View::make('logins.index');
        }

        public function postLogin(){
                //postされた値を取得
                $attrs = Input::only(['email', 'password']);

                //バリデーションチェック
                if (!$this->login->validate($attrs)) {
                    //問題があったらリダイレクト
                    return Redirect::action('LoginsController@getLogin')
                        ->withErrors($this->login->errors())
                        ->withInput();
                }

                //バリデーションを通過した後の処理を記述。今回はとりあえずecho
                echo "Validation Checked!";
         }
}

最後に、バリデーションの結果をViewに表示させるためにindex.blade.phpを編集

以下にforeachでエラーを表示。
後はお好みでinputのvalueにvalue="{{{ Input::old('email') }}}"というように値をセットすることで前回の入力を表示させることができる

<head>
        <meta charset="utf-8">
        <title>ログイン画面</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
        <div class="container" style="padding:20px 0">
                @foreach ($errors->all() as $error)
                  <p>{{{ $error }}}</p>
                @endforeach
                <form class="form-horizontal" style="margin-bottom:15px" action="{{ action('LoginsController@postLogin') }}" method="post">
                        <div class="form-group">
                                <label class="col-sm-2 control-label" for="email">Email</label>
                                <div class="col-sm-4">
                                        <input type="text" id="email" name="email" class="form-control" value="{{{ Input::old('email') }}}" placeholder="email">
                                </div>
                        </div>
                        <div class="form-group">
                                <label class="col-sm-2 control-label" for="password">Password</label>
                                <div class="col-sm-4">
                                        <input type="password" name="password" id="password" value="{{{ Input::old('password') }}}" class="form-control" placeholder="password">
                                </div>
                        </div>
                        <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-4">
                                <input type="submit" value="submit" class="btn btn-primary">
                        </div>
                </form>
        </div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>

終わり!次はデータベースにアクセスして整合性チェックをやりたい。。。

9
9
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
9
9