Home > other >  Can I change default foreign key for my Laravel Relationship?
Can I change default foreign key for my Laravel Relationship?

Time:07-19

I am currently working on a project that uses Laravel, but that was not using the relationships.

I set them a few months ago, but none of the tables id are set as variable_id but id_variable.

I quote Laravel doc.

Eloquent determines the foreign key of the relationship based on the parent model name.

In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method.

So that's what I did everywhere, but I want to know if I can set the default id key to a model? For the User model for example:

somthing like

default_foreign_key : 'id_user'

So that when I write

return $this->hasOne(User::class);

it uses id_user instead of user_id.

CodePudding user response:

Laravel has naming convention for relation/ db keys, but you can define custom keys, like it is described in One To One documentation

You can set foreign key name:

$this->hasOne(Phone::class, 'foreign_key');

and even you can define key names on both sides:

$this->hasOne(Phone::class, 'foreign_key', 'local_key');

CodePudding user response:

Yes, you can add foreign key as you wish:

$this->hasOne(User::class,'id_user');

You can create an abstract class extended from model and override this method inside of it:

public function getForeignKey()
{
    return Str::snake(class_basename($this)).'_'.$this->getKeyName();
}

and then extends your models from this custom model. (feel free for naming). I think this should work for you.

for your requirement I think the codes inside method should be like this:

 return $this->getKeyName().'_'.Str::snake(class_basename($this));

CodePudding user response:

Yes you can its also mentioned in the Laravel documentation

$this->hasOne(User::class, 'foreign_key', 'local_key');
  • Related