Laravel全局加入父table和所有视图中要访问的子

Laravel globally join the parent table and the children to be accessed in all views

我有三个表:

  1. users: 有id, name, email, password.
  2. profiles : 有 id, user_id, age, sex.
  3. addresses : 有 id, user_id, address, city, zip.

有什么方法可以将它们加入到所有视图中全局使用,而不是在每个控制器中都这样做吗?

所以,当我需要视图中的地址时,我可以通过简单地使用 {{Auth::user()->address}} 或类似的东西

来访问它

如果可以,能否请您举例说明如何实现?

如果你想像这样使用Auth那么你必须定义关系

User.php

public function address(){
 return $this->hasOne('YourAddressModel','user_id');
}

public function profile(){
   return $this->hasOne('YourProfileModel','user_id','id');
 }