Home > Blockchain >  email as a foreign key in larave
email as a foreign key in larave

Time:06-03

Can I make email as a foreign key ? $table->foreignId('email')->constrained('users')->onDelete('CASCADE'); . I wrote a seeder and is for an integer value for emai. I need to make email unique

This is my users table

        Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

CodePudding user response:

To create an Foreign Key association with email column of users table, you cannot use foreignId method as it creates unsignedBigInteger equivalent column.

You can create the foreign key association as

//Some other table - for eg lets say posts
Schema::create('posts', function(Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->string('author_email');

    $table->foreign('author_email') // a column on posts table
        ->references('email') //name of the column on users (referenced) table
        ->on('users')    //name of the referenced table 
        ->onDelete('cascade'); //constrain
});

Then using this foreign key association you can define the author relation in Post model linking it to the User model

//Post.php - eloquent model class
public function author()
{
    return $this->belongsTo(User::class, 'author_email', 'email');
}

Note: For this to work as expected, email column on users table must contain unique values i.e have a unique index (as you have in the migration of users table)

Laravel Docs - Migrations - Foreign Key Constraints

  • Related