How to customize Auth::user() columns with foreign key? Laravel

喜夏-厌秋 提交于 2019-12-11 06:50:41

问题


Firstly, everytime we login in laravel, the default is that the user(table) is always accessible by just using Auth::user().

See 2 tables below:
My struggle is, how can I add subscriber's columns to users(table) using subscriber_id from user table as foreign key.

My expectation is, I want all these(below) to be globally accessible after I logged in.

Auth::user()->name
Auth::user()->age
Auth::user()->gender
Auth::user()->marital_status
Auth::user()->subscriber_id
Auth::user()->subscriber_name
Auth::user()->subscriber_status
Auth::user()->subscriber_created_at
Auth::user()->subscriber_created_at

I been searching for an answer on google but none helps. I wish someone could help me to this.


回答1:


See the https://laravel.com/docs/5.7/eloquent-relationships

Set the relationship on Users model.

Example, for a one to one relation:

public function subscriber()
{
    return $this->hasOne('App\Subscribers', 'id', 'subscriber_id');
}



回答2:


I created Subscriber.php(model) consisting column above, and then I put below codes in my User.php(model):

public function subscriber()
{
    return $this->hasOne('App\Subscriber', 'id', 'subscriber_id');
}

And then to access all columns, I did these:

Auth::user()->name
Auth::user()->age
Auth::user()->gender
Auth::user()->marital_status
Auth::user()->subscriber_id

Auth::user()->subscriber->id
Auth::user()->subscriber->name
Auth::user()->subscriber->status
Auth::user()->subscriber->created_at
Auth::user()->subscriber->updated_at


来源:https://stackoverflow.com/questions/55129302/how-to-customize-authuser-columns-with-foreign-key-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!