Laravel カラム追加時にでたエラーNot null violation: 7 ERROR:


やりたいこと

"posts"テーブルに"part"というカラムを追加する。

使用環境

OS
docker
DB:postgres:12
デプロイ先:Heroku

つまづいたところ

php artisan migrateコマンド実行でエラー

$ docker-compose exec app sh //dockerコンテナに入るコマンド
/app# php artisan migrate 

SQLSTATE[23502]: Not null violation: 7 ERROR:  column "part" contains null values (SQL: alter table "posts" add column "part" varchar(255) not null)

エラーをよむ:新しく追加したカラム "part"はnull値を含んでいる。
(SQL: alter table "posts" add column "part" varchar(255) not null)
テーブルは追加カラム(varchar(255)=string)をnot nullで追加した

/app # php artisan migrate:status
+------+------------------------------------------------+-------+
| Ran? | Migration                                      | Batch |
+------+------------------------------------------------+-------+
| Yes  | 2014_10_12_000000_create_users_table           | 1     |
| Yes  | 2014_10_12_100000_create_password_resets_table | 1     |
| Yes  | 2019_08_19_000000_create_failed_jobs_table     | 1     |
| Yes  | 2021_04_02_083813_create_posts_table           | 1     |
| No   | 2021_04_10_202701_add_user_id_to_posts_table   |       |
+------+------------------------------------------------+-------+

migration状況確認。
Noになっています。

解決方法

app # php artisan migrate:refresh

すべてのマイグレーションをロールバックしmigrateを実行。
反映されました!!

Docker

Docker開発環境でpsqlにアクセスの仕方が分からなかったので;;
本番環境(Heroku)で確認

$ heroku pg:psql
:DATABASE=> \d posts
                                          Table "public.posts"
   Column   |              Type              | Collation | Nullable |              Default              
------------+--------------------------------+-----------+----------+-----------------------------------
 id         | bigint                         |           | not null | nextval('posts_id_seq'::regclass)
 title      | character varying(255)         |           | not null | 
 created_at | timestamp(0) without time zone |           |          | 
 updated_at | timestamp(0) without time zone |           |          | 
 user_id    | integer                        |           |          | 
 part       | character varying(255)         |           | not null | 

Nullable欄にnot nullと表記されている。
migrationファイルにnullable();と指定しない場合は、勝手にnot null制約をつけてくれる模様。

因みに...

$ heroku run php artisan migrate:fresh
Dropped all tables successfully.
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
//省略

とmigrate:refreshではなく、freshで全てのテーブルを削除しmigrateを実行でも大丈夫だった。
違いはdownの処理を行ってからmigrationするか、テーブルを全削除してから1からmigrationするか、らしいがここの使い分けは今はピンときていない。

参考URL

マイグレーション生成:LaravelドキュメントURL