LoginSignup
2
6

More than 3 years have passed since last update.

ユーザー登録の実装

Last updated at Posted at 2019-11-02

ユーザー登録の実装

手順
1.データベースを準備する
2.認証/登録機能クラスのコードを確認し、ルーティングに追加する
3.登録画面を作る

データベースを作成する

ユーザー情報を登録するテーブルを作成します。

migrationファイルの例です。



<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTweetsTable extends Migration
{

    public function up()
    {
        Schema::create('users', function (Blueprint $table) { //usersテーブル作成

            $table->increments('id');
            $table->string('name');
            $table->string('emails')->unique;
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}


上記を見てください。
upメソッドとdownメソッドの2つが定義されています。
これはマイグレーションファイル共通のメソッドで、
upメソッドには作成の処理
downメソッドにはupメソッドで作成した内容を元に戻す処理を記載します。

dropIfExistsメソッド
引数であるusersテーブルが存在していた場合、それを削除するメソッドです。

php artisan migrateコマンドでマイグレーションファイルを実行すればusersテーブルが作成されます。

認証/登録機能クラスのコードを確認し、ルーティングに追加する

登録処理は、RegisterControllerクラスの「showRegistractionFormメソッド」と「register」で行います。
両方のメソッドともLaravelのinstall時、既に用意されています。
RegisterController.phpは
app/Http/Controller/Authフォルダ内にあります。

しかし、その中には「showRegistractionFormメソッド」は見つかりません。
RegisterControllerがuseしている「RegistersUsers」トレイトに実装があります。

「RegistersUsers」トレイトは、vendorsフォルダのlaravel/framework/src/Illuminate/Foundation/Authフォルダにあります。確認して見ましょう。


public function showRegistrationForm()
    {
        return view('auth.register');
    }

showRegistrationFormメソッドでは、auth.registerの名のビューを表示します、テンプレート名のドット「.」はフォルダの区切りを表すため、「authフォルダの中のregisterビュー」を意味します。

registerメソッド


    public function register(Request $request)
    {
        $this -> validator($request->all())->validate();
        event(new Registered($user = $this->create($request->all())));
        $this->guard()->login($user);
        return $this->registered($request, $user)
                           ?: refirect($this->redirectPath());
    }

上記コード例に示す通り、validatorを使って入力値を確認して、createメソッドでデータベースに登録します。
続いてログイン処理を行って画面をリダイレクト指定します。
処理内で使用されているバリデーションルールやデータ登録の実装は、RegisterControllerクラスにあります。2つのファイルを行き来しながら処理を確認しましょう。

ルーティングを追加


Route::get('auth/register','Auth\RegisterController@showRegisterationForm');
Route::post('auth/register','Auth\RegisterController@register');

上記を追加することで/auth/registerにgetメソッドでアクセスした場合は、Auth\RegisterControllerクラスのshoeRegistrationForm関数が呼ばれ、/auht/registerへPOSTメソッドを使ってデータを送信した場合にはregister関数が呼ばれます。

登録画面を作る

会員登録の画面を作成します。
resource/views/authディレクトリにregister.blade.phpファイルを作成してください。

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>ユーザー登録フォーム</h1>
    <form class="" action=" auth/register" method="post">
      {{csrf_field()}}
      名前:<input type="text" name="name" size="30"><span>{{ $errors->first('name') }}</span><br />
      メールアドレス:<input type="text" name="email" size="30"><span>{{ $errors->first('email') }}</span><br />
      パスワード:<input type="password" name="password" size="30"><span>{{ $errors->first('password') }}</span><br />
      パスワード(確認):<input type="password" name="password_confirmation" size="30"><span>{{ $errors->first('password_confirmation' }})</span><br />
      <button type="submit" name="action" value="send">送信</button>
    </form>
  </body>
</html>

{{csrf_field()}}は、CSRFトークンを挿入するための記述です。
フレームワークの機能で画面表示の際に発行され、送信時に値チェックが行われます。

{{ $errors->first('name') }}は、送信ボタンを押した後、バリデーションで入力値をチェックするが、エラー時にエラー内容を表示するための記述です。

ボタンは、/auth/register画面に送信する設定です。

ログイン中は名前を表示し、それ以外は会員登録ボタンを表示させる

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    こんにちは
    @if(Auth::check())
    {{ \Auth::user()->name }}さん
    @else
    ゲストさん <br />
    <a href="/auth/register">会員登録</a>
    @endif

  </body>
</html>

Auth::check()でログイン状態を確認し、ログインしていれば trueを返します。

2
6
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
2
6