Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use foreignId-constrained with default value?

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))

like image 611
schutte Avatar asked Oct 19 '25 14:10

schutte


1 Answers

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');
like image 165
Parsa_Gholipour Avatar answered Oct 22 '25 03:10

Parsa_Gholipour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!