Laravel ミニブログ作成2 認証を実装

Laravel Breezeパッケージで実装

Laravel Breezeパッケージの追加

プロジェクトディレクトリで

sail composer require laravel/breeze --dev

Laravel Breezeパッケージのインストール

sail artisan breeze:install

マイグレーションの実行

sail artisan migrate

依存関係のインストール

package.jsonにTailwind CSS とAlpine.jsが追記されるので、npm でパッケージを一括インストール

npm install

アセットのビルド

npm run build

ログインの確認

localhost/

  • 会員登録
  • ログイン
    を確認

認証を日本語化

エラーメッセージの日本語化

CLIで以下のコマンドを実行

php -r "copy('https://readouble.com/laravel/8.x/ja/install-ja-lang-files.php', 'install-ja-lang.php');"
php -f install-ja-lang.php
php -r "unlink('install-ja-lang.php');"
  1. 日本語化ファイルをインストールするためのスクリプトを、install-ja-lang.phpという名前でダウンロードする
  2. 1でダウンロードしたinstall-ja-lang.phpファイルを実行する(resources/lang/jaフォルダの中に各種日本語化ファイルが生成される)
  3. 不要になったinstall-ja-lang.phpファイルを削除する

resources/lang/jaフォルダの中に生成されたvalidation.phpというファイルには、日本語化されたエラーメッセージが記述されている。

次にconfigディレクトリのapp.phpを編集する。

- 'locale' => 'en'
+'locale' => ja 

各ページの表記の日本語化

各ページの__()ヘルパー関数が指定したキーに一致した値を返す。
config/app.phpファイルのlocalejaを指定した場合はresource/langディレクトリ内のja.jsonファイルが参照される。

resouces/langディレクトリにja.jsonファイルを作成。__()に対応する文字列を登録しておく。
ja.json

{
      "Email": "メールアドレス",
      "Password": "パスワード",
      "Remember me": "ログイン状態を保存する",
      "Log in": "ログイン",
      "Forgot your password?": "パスワードをお忘れですか?",
      "Name": "ユーザー名",
      "Confirm Password": "パスワード(確認用)",
      "Register": "登録",
      "Already registered?": "すでに登録済みですか?",
      "Forgot your password? No problem. Just let us know your email address and we will email you a password reset link that will allow you to choose a new one.": "パスワードをお忘れですか?ご心配なく。メールアドレスをお知らせいただければ、パスワード再設定用のリンクをメールでお送りします。",
      "Email Password Reset Link": "パスワード再設定用リンクの送信",
      "Reset Password": "パスワード再設定",
      "Thanks for signing up! Before getting started, could you verify your email address by clicking on the link we just emailed to you? If you didn't receive the email, we will gladly send you another.": "ご登録ありがとうございます!ご利用を開始する前に、メールアドレスをご確認ください。メールが届いていない場合は、再度お送りいたします。",
      "A new verification link has been sent to the email address you provided during registration.": "ご登録いただいたメールアドレスに新しい認証リンクを送信しました。",
      "Resend Verification Email": "認証メールの再送信",
      "Profile": "アカウント",
      "Log Out": "ログアウト",
      "Dashboard": "ダッシュボード",
      "You're logged in!": "ログインしました!",
      "Profile Information": "アカウント情報",
      "Update your account's profile information and email address.": "アカウント情報とメールアドレスを更新できます。",
      "Your email address is unverified.": "メールアドレスが未確認です。",
      "Click here to re-send the verification email.": "こちらをクリックして認証メールを再送信してください。",
      "A new verification link has been sent to your email address.": "あなたのメールアドレスに新しい認証リンクを送信しました。",
      "Save": "保存",
      "Saved.": "保存しました。",
      "Update Password": "パスワード更新",
      "Ensure your account is using a long, random password to stay secure.": "アカウントの安全性を保つために、長くてランダムなパスワードを使用してください。",
      "Current Password": "現在のパスワード",
      "New Password": "新しいパスワード",
      "Delete Account": "アカウント削除",
      "Once your account is deleted, all of its resources and data will be permanently deleted. Before deleting your account, please download any data or information that you wish to retain.": "アカウントを削除すると、関連するすべてのデータが永久に削除されます。アカウントを削除する前に、必要に応じてデータをバックアップしてください。",
      "Are you sure you want to delete your account?": "本当にアカウントを削除してもよろしいですか?",
      "Once your account is deleted, all of its resources and data will be permanently deleted. Please enter your password to confirm you would like to permanently delete your account.": "アカウントを削除すると、関連するすべてのデータが永久に削除されます。アカウントを削除してよろしければ、パスワードを入力してください。",
      "Cancel": "キャンセル",
      "Verify Email Address": "メールアドレス確認",
      "Hello!": "こんにちは!",
      "Please click the button below to verify your email address.": "下のボタンをクリックしてメールアドレスを確認してください。",
      "If you did not create an account, no further action is required.": "心当たりがない場合は、本メールを破棄してください。",
      "Regards": "よろしくお願いいたします",
      "If you're having trouble clicking the \":actionText\" button, copy and paste the URL below\ninto your web browser:": "「:actionText」ボタンを押しても何も起きない場合、以下のURLをコピーしてWebブラウザに貼り付けてください。",
      "Reset Password Notification": "パスワード再設定のお知らせ",
      "You are receiving this email because we received a password reset request for your account.": "あなたのアカウントでパスワード再設定のリクエストがありました。",
      "This password reset link will expire in :count minutes.": "このパスワード再設定リンクの有効期限は :count 分です。",
      "If you did not request a password reset, no further action is required.": "心当たりがない場合は、本メールを破棄してください。"
    }

メール認証

メール認証機能を有効

LaravelにはMustVerifyEmailというインターフェースがもともと用意されており、これをUserモデルに実装するだけ
インターフェース=メソッドやプロパティの名前のみを定義したもの(メソッドやプロパティの具体的な中身は記述しない)。複数のクラスに共通の機能を持たせたいときに使う 。

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
+ use Illuminate\Contracts\Auth\MustVerifyEmail;

+ class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];
}

Gmailでメールの送信処理を実装

  1. Googleアカウントの2段階認証プロセスを有効にする
    Googleアカウントのトプページ
    「セキュリティ」->「2段階承認プロセス」から2段階承認を設定完了させる
  2. アプリパスワードを生成する
    「アプリパスワード」の>をクリック、「App name」にアプリ名を入力し「作成」
    パスワードが生成されるのでコピー
  3. GmailSMTPサーバーに設定
    .envファイルのMAIL設定を編集
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME="アプリパスワードを発行したアカウントのGmailアドレス"
MAIL_PASSWORD="アプリパスワード"
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="アプリパスワードを発行したアカウントのGmailアドレス"
MAIL_FROM_NAME="${APP_NAME}"