mysqllaravelforeign-keysforeign-key-relationship

MySQL Laravel making foreign key unique


In my app built using Laravel/Mysql I have two tables for users.

When I user register the table "User" and "UserInfo" gets created.

UserInfo has a FK that points to the PK in the Users table.

Right now I have a column in my UserInfo table that is set to unique I do this to make sure that user only can have one record in the UserInfo table.

But is it possible to just make the FK unique? I need a one-to-one design between the tables.


Solution

  • You can just make the integer itself unique. The foreign method is only used to link those datas between table A and table B.

    $table->integer('user_id')->unsigned()->unique();
    $table->foreign('user_id')->references('id')->on('user_infos');
    

    What you are probably looking for is Eloquent:Relationships and must be added to your Models.

    You can add this for your UserInfo Model:

    public function user()
    {
        return $this->belongsTo(UserInfo::class);
    }
    

    And this for your User Model:

        public function user_info()
    {
        return $this->hasOne(User::class);
    }
    

    Further information: https://laravel.com/docs/5.2/eloquent-relationships#defining-relationships