2
0

【PHP / Laravel】現在のパスワードと一致するか確認するバリデーション

Last updated at Posted at 2023-12-21

株式会社やどかりの平山です。
パスワード変更画面での実装について書かせていただきます。


〜やりたいこと〜
【現在のパスワード】が正しいものか検証し、 正しくなければバリデーションメッセージを表示したい

552c3a971ec10167a0b72e35b2eace93.png



①ターミナルに下記を入力
ターミナル
php artisan make::rule CurrentPasswordRule

② ①で作成したCurrentPasswordRule.phpに必要事項を記述
(パスワードはセキュリティのためHash化しています)

CurrentPasswordRule.php
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class CurrentPasswordRule implements Rule
{
    public function passes($attribute, $value)
    {
        // ユーザーがログインしているかを確認
        if (Auth::check()) {
            // ユーザーの現在のパスワードを取得
            $currentPassword = Auth::user()->password;

            // 入力されたパスワードが現在のパスワードと一致するかどうかを確認
            return Hash::check($value, $currentPassword);
        }

        return false;
    }

    public function message()
    {
        return '現在のパスワードが正しくありません。';
    }
}

③エラーメッセージを表示したい箇所(bladeファイル内)に記述

password_change.blade.php
//見出し部分
<th>{!! Form::label('currentPassword', '現在のパスワード') !!}</th>
<td>
    //フォーム部分
    {!! Form::password('currentPassword', ['id' => 'currentPassword', 'class' => 'col-12 form-control border', 'placeholder' => '現在のパスワードを入力してください']) !!}
    //エラーメッセージ部分
    @error('currentPassword')
        <div class="text-danger">
            {{ $message }}
        </div>
    @enderror
</td>

④Controllerに記述

SettingController.php
use App\Rules\CurrentPasswordRule;

public function passwordChange(Request $request)
{
    $request->validate([
        'currentPassword' => ['required', new CurrentPasswordRule],
        // 他のバリデーションルールを追加
    ]);

    // パスワードを更新する処理などを記述
}

⑤routeを設定

web.php
Route::post('setting/password_change', [SettingController::class, 'passwordChange'])->name('setting.change_password.update');
2
0
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
0