1
0

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 でのパスワードの設定で気をつけること

Posted at

この記事の背景

共同開発をしていた時に編集と更新機能を作っていました。
その時にうまくログインできなかったり、パスワードがちゃんと設定されていなくて
詰まってしまいました。その時の経験をベースに書いていきます。

どんな画面か

スクリーンショット 2023-04-17 0.14.01.png

バリデーション

まずバリデーションがちゃんとかかっているかの確認が大切です。
設定したバリデーション通りに編集画面などで自分で挙動を確認するテストをする必要があります。必須です。
下のコードを解説すると

・名前、メールアドレス、パスワードは必須で文字列である必要がある。
・名前、メールアドレスの文字数は最高で255文字までが上限です。
・メールアドレスは自分自身のメールアドレスと重複しないようにする。
・パスワードは最低8文字は入力しなければならない。
・'confirmed'は、'password'と同じ値が確認用に入力されたことを確認し、
password_confirmationが存在し、一致しなければならないと言う意味です。

UserRequest.php
public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required', 'string', 'email', 'max:255',Rule::unique('users')->ignore($this->id)
            ],
            'password' => ['required', 'string',  'min:8', 'confirmed'],
        ];
edit.blade.php

        <div class="form-group">
            <label for="password">パスワード</label>
            #省略
        </div>
        <div class="form-group">
            <label for="password_confirmation">パスワードの確認</label>
            <input id="password_confirmation" type="password" class="form-control" name="password_confirmation" value="{{ old('password_confirmation') }}">
        </div>

old関数が必要

old関数は忘れずに入れましょう!忘れると例えばユーザーの情報を更新した後に下の画像みたいになってしまいます。

スクリーンショット 2023-04-25 12.53.02.png

edit.blade.php
#省略
<div class="form-group">
            <label for="password">パスワード</label>
            <input id="password" type="password" class="form-control" name="password" value="{{ old('password') }}">
        </div>
        <div class="form-group">
            <label for="password_confirmation">パスワードの確認</label>
            <input id="password_confirmation" type="password" class="form-control" name="password_confirmation" value="{{ old('password_confirmation') }}">
        </div>

bcrypt

ユーザーデータの更新でパスワードを更新する処理をコントローラーに書いた時にbcryptを忘れてしまいました。
bcryptはパスワードをハッシュ化することでセキュリティを高めるみたいです。

usersController.php
public function update(UserRequest $request, $id)
    {
       #省略
        $user->password = bcrypt($request->password);
        $user->save();
        #省略
    }

まとめ

自分はこれらを忘れてしまってPRを1回出してしまいました。
みなさん初歩的なミスですが、気をつけてください。

資料

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?