1
3

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 3 years have passed since last update.

laravel 電話番号の型の設定とDBに保存する方法

Posted at

はじめに

登録する際に電話番号も登録できるようにしたところ、phpMyAdminで確認すると電話番号の最初の0が消えていたのでこれを0から登録できるように改良します!!
スクショで以下のようになっているのでこれを修正します。
“スクリーンショット” 2021-02-17 18.41.28.jpg

投稿者の環境

MacBook Pro (13-inch, 2019, Two Thunderbolt 3 ports)
macOS Big Sur バージョン11.0.1
PHP 7.3.23
Laravel Framework 6.20.7

ステップ1 電話番号のバリデーションの設定

電話番号は10桁または11桁になります。バリデーションを10桁または11桁にします。

RegisterController.php
'phone' => ['required','numeric','digits_between:10,11'],

ステップ2 電話番号のデータ型の設定

ここで自分はどハマりして中々突破できませんでした。
結論から言うと、電話番号の型はunsignedBigIntegerにします。

add_column_to_users_table.php
$table->unsignedBigInteger('phone')->after('address');//電話番号

データ型int(11)にするとMysql「Warning: #1264 Out of range value for column 'カラム名' at row 1)」とエラーが出ます。理由は以下のスクショになります
“スクリーンショット” 2021-02-17 19.06.43.jpg

ステップ3 電話番号を0から表示するように設定

このまま登録をしたとしても、0から表示はされません。phpMyAdminで0から表示されるように変更します。属性のところをUNSIGNED ZEROに変更します。最後に保存するを選択
“スクリーンショット” 2021-02-17 19.14.10.jpg
このように表示されると思います。
“スクリーンショット” 2021-02-17 19.25.50.jpg

最後に

数字のデータ型を全てint型にするとこのようなエラーに遭遇する可能性があるのでもっと知るべきだなと思った出来事になりました。

参考URL

電話番号の桁数のQiita
電話番号カラムのデータ型とその扱い[PHP][MYSQL][データ型][int型][integer][桁あふれ][telカラム]

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?