How to set the foreign key name in php laravel?

Viewed 4792

How can I set the name of a foreign key in php laravel?

Schema::table('TABLE_NAME', function (Blueprint $table) {
        $table->foreign(XXX)
            ->references(XXX)
            ->on('REF_TABLE')
            ->onDelete('cascade');

            // HOW TO ACHIEVE SOMETHING LIKE THIS?
            //->name('Custom name of foreign key.')
            //->comment('Custom comment for foreign key.')        
    });
3 Answers

You can specify a custom name by filling the second foreign param :

->foreign('XXX', 'my_custom_name')

when you build your foreign key column, you can build it like:

 $table->UnsignedBigInteger('xxx')->comment("comment for this column");

see this link.

you can also find the details in Laravel column-modifiers.

You can make the foreign key in the following way:-

        $table->unsignedInteger('XXXX')
            ->nullable();
        $table->foreign('XXXX')
            ->references('id')
            ->on('REF_TABLE')
            ->onDelete('cascade');
Related