问题
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