Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

krunal05's avatar

set a foreign key to nullable in Laravel 8

I have 'signs' table in that, I have unsigned 'po_id' as a foreign key which is not nullable at the moment.

How to I make it nullable. Do i have to compulsory drop the column first?

0 likes
6 replies
s4muel's avatar
s4muel
Best Answer
Level 50

if you use migrations, create new one and change the column via new migration

...
Schema::table('signs', function (Blueprint $table) {
    //use your current column type instead of unsignedBigInteger, if needed
    $table->unsignedBigInteger('po_id')->nullable()->change();
});
...

if not, update the column manually in a database client of your choice

3 likes
krunal05's avatar

Thanks for the quick reply. Yes i am using migration. what about the down() ?

would that be? :

$table->unsignedBigInteger('po_id')->nullable(false)->change();
tykus's avatar

Should be enough in the down method to leave out the nullable method call.

1 like
jlrdw's avatar

Normally you would want those child id's like an invoice:

But for a one time receipt that would be different. But not sure what you are doing with your master detail data.

1 like
krunal05's avatar

@jlrdw How do you attach the image here loll sorry i am new here.

But i have to follow this due to weird client requirement.

lets say my signs table has two foreign ids project_id & po_id.

Think signs as a products. projects can have many signs/products. Instead of i suggest to have coupons client wants to add another sign which will have negative value and that will act as a coupon. so this wont have any po_id relation. Its weird. Our company also did not recommend this solution but they said thats how they are maintaining their sheet till date. and they want to follow this way.

krunal05's avatar

@s4muel this worked great for me.

 /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('signs', function (Blueprint $table) {
            $table->unsignedBigInteger('po_id')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('signs', function (Blueprint $table) {
            $table->unsignedBigInteger('po_id')->nullable(false)->change();
        });
    }
4 likes

Please or to participate in this conversation.