tjtjtjのメモ

自分のためのメモです

laravel はじめました

公式ドキュメントを購入したのは先月だったか。ようやくはじめた。

はじめて書いたコード

見よう見まねで書いたログインフォームがこれ。 action_login と action_dologin で同じものをviewに渡そうとゴニョゴニョしていますね。

controllers/auth.php

<?php
class Auth_Controller extends Base_Controller {

    public function action_login()
    {
        $input = array('username' => '');
        return View::make('auth.login')
                ->with('input', $input)
                ->with('errors', new Laravel\Messages());
        }

    public function action_dologin()
    {
        $input = Input::all();
        $rules = array(
                'username' => 'required',
                    'password' => 'required',
        );
        $validation = Validator::make($input, $rules);
        if ($validation->fails())
        {
            return View::make('auth.login')
                    ->with('input', $input)
                    ->with('errors', $validation->errors);
            }
            return "authed!";
    }
}

views/auth/login.blade.php

{{ Form::open('auth', 'post') }}

{{ Form::text('username', $input['username']) }}
@if ($errors->has('username'))
    {{ $errors->first('username') }}
@endif

{{ Form::password('password') }}
@if ( $errors->has('password'))
    {{ $errors->first('password') }}
@endif

{{ Form::submit() }}
{{ Form::close() }}

書き直したコード

ドキュメントとかソースとか読み直して、書き直したのがこれ。action_login からバリデーション失敗時のコードがなくなりすっきりしました。

controllers/auth.php

<?php
class Auth_Controller extends Base_Controller {

    public function action_login()
    {
        return View::make('auth.login');
    }

    public function action_dologin()
    {
        $input = Input::all();
        $rules = array(
                'username' => 'required',
                'password' => 'required',
        );
        $validation = Validator::make($input, $rules);
        if ($validation->fails())
        {
            return Redirect::back()
                ->with_input()
                ->with_errors($validation);
        }
        return "authed!";
    }
}

views/auth/login.blade.php

{{ Form::open('auth', 'post') }}
{{ Form::text('username', Input::old('username')) }}
{{ $errors->first('username') }}
{{ Form::password('password') }}
{{ $errors->first('password') }}
{{ Form::submit() }}
{{ Form::close() }}

わかったこと

バリデーションエラーで前のページに戻るときは、Redirect::back()

あわせて with_input(), with_errors() も使う


Input::old() で前回入力した値を得られる
そのために with_input() しておく


view に空の errors を渡す必要はない
Viewコンストラクタ で $this->date['errors'] = new Messages() している。
エラーメッセージのキーは errors とするのが laravel の流儀っぽい


バリデーションメッセージ表示は {{$errors->first('fieldname')}}
エラーがなければ何もしないから if いらない