Search code examples
laravel-9

Using foreign key in controllers Laravel 9


I was creating two tables user and user_info and i want to use the userid in userinfo. I don't know how to use the userid in userinfocontroller.


Solution

  • You must define one to one relation in your models. in User Model :

        public function info()
        {
             return $this->hasOne(Info::class,'foreign key'); // (Info = your userinfo model)
        } 
    

    and in your Info model :

        public function user()
        {
              return $this->belongsTo(User::class, 'foreign key');
        }
    

    you can read documents too.