1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel】Password::defaults()でバリデーション

Last updated at Posted at 2024-05-05

開発環境

Laravel10
Windows11

目的

アプリケーション作成時にパスワード検証を何度も行うため、何度も同じ処理を書くのがめんどい。

→デフォのパスワードルールを作成。

公式ドキュメント

設定可能な項目

// 最低8文字
Password::min(8)

// 1文字以上のアルファデットを含む
Password::min(8)->letters()

// 大文字と小文字のアルファベットを含む
Password::min(8)->mixedCase()

// 1文字以上の記号を含む
Password::min(8)->symbols()

// 漏洩済みパスワードでないか
Password::min(8)->uncompromised()

※上記はほぼ引用
[引用:https://zenn.dev/nshiro/articles/e6549d83211363]

AppServiceProvider

AppServiceProviderのboot()で実装。

AppServiceProvider.php
use Illuminate\Validation\Rules\Password;

    public function boot(): void
    {
        return Password::min(8)->letters()
                                ->mixedCase()
                                ->numbers()
                                ->symbols()
                                ->uncompromised();
    }

本番環境

AppServiceProvider.php
public function boot()
{
    Password::defaults(function () {
        $rule = Password::min(8);
 
        return $this->app->isProduction()
                    ? $rule->mixedCase()->uncompromised()
                    : $rule;
    });
}

$this->app->isProduction()で現在の実行環境が本番環境であるかを判定。

判定基準は.envAPP_ENV
下記の記述になっている場合は、本番環境と認識する。

APP_ENV=production

Request

設定したデフォのルールは下記の通り記述することで適用される。

TestRequest.php
    public function rules(): array
    {
          'password' => ['required', 'confirmed', Password::default()],
    }

参考記事

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?