schutte
schutte

Reputation: 2166

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

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:
enter image description here 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.

Upvotes: 1

Views: 1910

Answers (2)

schutte
schutte

Reputation: 2166

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

Upvotes: 0

JoaoGRRR
JoaoGRRR

Reputation: 315

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');
}

Upvotes: 5

Related Questions