'How to create foreign keys in Laravel without errors
I'm trying to create foreign keys in Laravel. However, when I migrate my table using Artisan, I am thrown the following error.
Schema::create('billing_transactions', function (Blueprint $table) {
    $table->id();
    $table->integer('payment_amount')->default(0);
    $table->tinyInteger('status')->default(0);
    $table->foreignIdFor(PatientVisit::class)->nullable()->constrained()->onDelete('cascade')->onUpdate('cascade');
    $table->foreignIdFor(BillingInvoice::class)->nullable()->constrained()->onDelete('cascade')->onUpdate('cascade');
    $table->foreignId('created_by_id')->nullable()->constrained('users')->onDelete('cascade')->onUpdate('cascade');
    $table->foreignId('updated_by_id')->nullable()->constrained('users')->onDelete('cascade')->onUpdate('cascade');
    $table->timestamps();
});
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table
billing_transactionsadd constraintbilling_transactions_billing_invoice_id_foreignforeign key (billing_invoice_id) referencesbilling_invoices(id) on delete cascade on update cascade)
Solution 1:[1]
    /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->BigInteger('role_id')->unsigned();
        $table->BigInteger('lang_id')->unsigned()->nullable();
        $table->BigInteger('reference_id')->unsigned()->nullable()->default(null);
        $table->string('name');
        $table->string('surname');
        $table->boolean('blocked')->default(0);
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
    Schema::table('users', function($table) {
        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->foreign('lang_id')->references('id')->on('languages')->onDelete('cascade');
        $table->foreign('reference_id')->references('id')->on('users')->onDelete('cascade');
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('users', function($table) {
        $table->dropForeign(['role_id']);
        $table->dropColumn('role_id');
        $table->dropForeign(['lang_id']);
        $table->dropColumn('lang_id');
        $table->dropForeign(['reference_id']);
        $table->dropColumn('reference_id');
        $table->dropUnique(['email']);
        $table->dropColumn('email');
    });
    Schema::dropIfExists('users');
}
I use like that. For foreigns and uniques.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Deniz Gölbaş | 
