Laravel ECサイト step03

認証

Laravel Breeze追加

  • breezeパッケージの追加 sail composer require'laravel/breeze:*' --dev
    :* の意味「利用可能な任意のバージョン」
  • Laravel Breezeパッケージのインストール
    sail artisan breeze:install
質問 回答
Which Breeze stack would you like to install?(どのBreezeスタックをインストールしますか?) 0
Would you like dark mode support?(ダークモードをサポートしますか?) no
Would you prefer Pest tests instead of PHPUnit?(PHPUnitの代わりにPestを使いますか?) no
  • ルーティングの復元
<?php

use App\Http\Controllers\ProfileController;
+use App\Http\Controllers\ProductController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

require __DIR__.'/auth.php';

+Route::resource('products', ProductController::class);
  • 依存関係のインストール npm install

  • アセットのビルド
    npm run build

urlにアクセスするとログインと会員登録ページのリンクが追加されている。

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

以下のコマンドを実行

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ファイルを開き、以下のように編集

config/app.php

    /*
    |--------------------------------------------------------------------------
    | Application Timezone
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default timezone for your application, which
    | will be used by the PHP date and date-time functions. We have gone
    | ahead and set this to a sensible default for you out of the box.
    |
    */

    'timezone' => 'Asia/Tokyo',

    /*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Application Fallback Locale
    |--------------------------------------------------------------------------
    |
    | The fallback locale determines the locale to use when the current one
    | is not available. You may change the value to correspond to any of
    | the language folders that are provided through your application.
    |
    */

    'fallback_locale' => 'en',

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

resources/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.": "心当たりがない場合は、本メールを破棄してください。"
    }

メール認証の有効化

  • メール認証機能を有効

app/Models/User.phpを編集

<?php

namespace App\Models;

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

-class User extends Authenticatable
+class User extends Authenticatable implements MustVerifyEmail
{
    //======== 中略 ========
}
  • Laravelプロジェクトとメールサーバーを連携

    1. Gmailの2段階認証プロセスを有効に
      Googleアカウントのトップページ
      「アプリパスワード」 > 「App name」にアプリ名を入力してパスワードを生成
    2. GmailSMTPサーバーに設定
      .envを編集
#========  前略 ========

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
-MAIL_HOST=mailpit
+MAIL_HOST=smtp.gmail.com
-MAIL_PORT=1025
+MAIL_PORT=587
-MAIL_USERNAME=null
+MAIL_USERNAME=アプリパスワードを発行したアカウントのGmailアドレス
-MAIL_PASSWORD=null
+MAIL_PASSWORD=アプリパスワード
-MAIL_ENCRYPTION=null
+MAIL_ENCRYPTION=tls
-MAIL_FROM_ADDRESS="hello@example.com"
+MAIL_FROM_ADDRESS=アプリパスワードを発行したアカウントのGmailアドレス
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

#========  後略 ========

リダイレクト先を変更

  • 会員登録後 app/Http/Controllers/Auth/RegisteredUserController.phpを編集
//========  前略 ========

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

        Auth::login($user);

-        return redirect(RouteServiceProvider::HOME);
+        return redirect('/verify-email');
    }
}
  • ログイン後
    app/Providers/RouteServiceProvider.phpを編集
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to your application's "home" route.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */
-     public const HOME = '/dashboard';
+     public const HOME = '/';

//======== 後略 ========