Written by Manabu Bannai

Laravelで『ログイン/ログアウト処理』を実装したのでコードを公開します。

Laravel PROGRAMMING

Laravelでログイン/ログアウト処理を作成しました。
備忘録的に開発手順を公開しておきます。
完成予想図は以下です。
ログイン/ログアウト

ログイン処理のルーティング設定


// ログインページを表示させるルーティング
Route::get('login', array('uses' => '[email protected]'));

// ログインページのポスト機能のルーティング
Route::post('login', array('uses' => '[email protected]'));

// ログアウト処理のルーティング
Route::get('logout', array('uses' => '[email protected]'));

ログイン処理のメソッドをホームコントローラーに記述する


public function showLogin()
{
	return View::make('login');
}

public function doLogin(){
	$credentials = [
		'email'=>Input::get('email'),
		'password'=>Input::get('password')
	];

	$rules = [
		'email'=>'required',
		'password'=>'required'
	];

	$messages = array(
		'email.required' => 'メールアドレスを正しく入力してください。',
		'password.required' => 'パスワードを正しく入力してください。',
	);

	$validator = Validator::make($credentials, $rules, $messages);

	if ($validator->passes()) {
		if (Auth::attempt($credentials)) {
			// ここではリダイレクト先を/loginに設定していますが、ここは状況に応じて変更してください
			return Redirect::to('login')
				->with('success', 'ログインしました。');
		}else{
			return Redirect::back()->withInput();
		}
	}else{
		return Redirect::back()
			->withErrors($validator)
			->withInput();
	}
}

public function doLogout()
{
	Auth::logout();
	return Redirect::to('login');
}

つぎにログインのビューを作成します。

@extends('layouts.default')
@section('content')

<h1>ログイン</h1>

{{-- ログイン時にフラッシュメッセージを表示 --}}
@if(Session::has('success'))
	<div class="bg-info">
		<p>{{ Session::get('success') }}</p>
	</div>
@endif

{{ Form::open(array('url' => 'login', 'class' => 'form-horizontal')) }}

	<div class="form-group">
		{{-- バリデーションのエラー表示 --}}
		@foreach($errors->get('email') as $message)
			<span class="bg-danger">{{ $message }}</span>
		@endforeach
		<label for="email" class="col-sm-2 control-label">メールアドレス</label>
		<div class="col-sm-10">
			{{ Form::text('email',Input::old('email'), array('class' => 'form-control')) }}
		</div>
	</div>

	<div class="form-group">
		{{-- バリデーションのエラー表示 --}}
		@foreach($errors->get('password') as $message)
			<span class="bg-danger">{{ $message }}</span>
		@endforeach
		<label for="password" class="col-sm-2 control-label">パスワード</label>
		<div class="col-sm-10">
			<input name="password" type="password" class="form-control">
		</div>
	</div>

	<div class="form-group">
		<button type="submit" class="btn btn-primary">ログインする</button>
	</div>

{{ Form::close() }}

@stop

これで完成です。とても簡単ですね。

番外編:ログインしているorしていないユーザーでルーティングを切り替える

以下のように記述することで、ログインしているorしていないユーザーで条件分岐できます。
編集ファイル:app/routes.php


Route::get('[アクセス禁止先のURL]', array(
	'before' => 'auth',
	function(){
		// ログイン済のユーザーはリダイレクト
		return View::make('[リダイレクト先のURL]');
	}
));