Search code examples
phplaraveleloquentlaravel-authentication

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.


Solution

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