2018/10/12

前回、新規登録画面を作成しました。
今回はログイン画面を作成して新規登録で登録した情報でログインするところまでやります。
ログイン画面も会員登録画面と同様に
【1】最初に表示するログイン画面(getメソッド)
【2】POST送信された値をDBの値と照合する処理(postメソッド)
の2種類を作成します。
【1】ログイン画面(get)
まずはログイン画面を表示させてみます。
View
@extends('layouts.master_auth')
@section('content')
<div class="row">
<div class="col-md-4 col-md-offset-4">
<h1>Sign In</h1>
@if(count($errors) >0)
<div class="alert alert-danger">
@foreach($errors->all() as $error)
<p>{{ $error }}</p>
@endforeach
</div>
@endif
<form action="{{ route('user.signin') }}" method="post">
<div class="form-group">
<label for="email">E-Mail</label>
<input type="text" id="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" class="form-control">
</div>
<button type="submit" class="btn btn-primary">ログイン</button>
{{ csrf_field() }}
</form>
</div>
</div>
@endsection
Routing
:
Route::get('/signin',[
'uses' => 'UserController@getSignin',
'as' => 'user.signin'
]);
:
Controller
:
public function getSignin()
{
return view('user.signin');
}
:
動作確認
http://{ローカルホスト}/user/signin
【2】ログインからのPOST処理
Routing
:
Route::post('/signin',[
'uses' => 'UserController@postSignin',
'as' => 'user.signin'
]);
:
Controller
ログイン画面でPOST送信された値を処理します。
バリデーション ⇒ 認証(attemptメソッド) ⇒ リダイレクト
:
public function postSignin(Request $request)
{
$this->validate($request,[
'email' => 'email|required',
'password' => 'required|min:4'
]);
if(Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])){
return redirect()->route('user.profile');
}
return redirect()->back();
}
:
attemptメソッドを使うにはAuthファサードを使います。
冒頭にAuthをインポートしておきます。
⇒ use Auth;
冒頭にAuthをインポートしておきます。
⇒ use Auth;
View
ログイン後のページの文言もわかりやすく書き直しておきます。
@extends('layouts.master_auth')
@section('content')
<div style="margin-top: 30px; text-align: center;"><h3>ログイン成功!</h3></div>
@endsection
動作確認
1.ログイン画面で新規登録したe-mailとpasswordを入力
2.プロファイル画面にリダイレクトされたか確認
ログイン画面については以上です。
仕事で Laravel を使っています。気づいたことや新しい発見など情報を発信していきます。問い合わせはこちら。


