3

It's just now that I noticed from the video tutorial that Laravel has this foreignId-constrained. So I try change my code from method.1 to method.2, the table migrated but when I try to db:seed, the default value is not working (it returns an error below).

(Method.1)

$table->unsignedBigInteger('status_id')->default(1);

$table->foreign('status_id')
    ->references('id')
    ->on('user_statuses');

(Method.2)

$table->foreignId('status_id')->constrained('user_statuses')->default(1);

(Error returned using method.2)

SQLSTATE[HY000]: General error: 1364 Field 'status_id' doesn't have a default value (SQL: insert into users (username, password) values (admin, $2y$10$S ZUIglBQG/HhS/18zn41GOcH8f.hZaNewmyoGJBfDQchfC6OWdx26))

miken32
  • 42,008
  • 16
  • 111
  • 154
schutte
  • 1,949
  • 7
  • 25
  • 45

1 Answers1

8

According to the documentation, you are calling methods in the wrong order:

Any additional column modifiers must be called before the constrained method

$table->foreignId('status_id')->default(1)->constrained('user_statuses');
miken32
  • 42,008
  • 16
  • 111
  • 154
Parsa_Gholipour
  • 794
  • 5
  • 16