Home  >  Q&A  >  body text

How to add new value to "auth()" function after login?

<p>I am developing a project using Laravel 8. </p> <p>There are some fields in my Users table, such as "us_name", "us_surname". Once the user is logged in, I can get these values ​​via "auth()->user()->us_name" etc. So far, no problems. </p> <p>What I want to do is add some values ​​here that are not in my table. For example, after logging in, combine first and last name and add a new field called "us_fullname" and access it via "auth()->user()->us_fullname". How can I do this? </p>
P粉354948724P粉354948724435 days ago366

reply all(1)I'll reply

  • P粉351138462

    P粉3511384622023-09-04 12:39:52

    You can get the Authenticatable model from the default guard by calling auth()->user().

    Let’s take a look at the default config/auth.php

    <?php
    
    return [
        'defaults' => [
            'guard' => 'web',
            'passwords' => 'users',
        ],
        'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
    
            'api' => [
                'driver' => 'token',
                'provider' => 'users',
                'hash' => false,
            ],
        ],
        'providers' => [
            'users' => [
                'driver' => 'eloquent',
                'model' => App\Models\User::class,
            ]
        ]
    ];

    With this default Laravel configuration, you get:

    1. The default guard is web
    2. web The guard provider (providing Authenticatable) is users
    3. usersThe provider provides App\Models\User::class
    4. App\Models\User implements AuthenticatableContract

    Then, by calling auth()->user() - you will get an instance of App\Models\User::class or null

    Answer your question

    You can add anything to the User model (e.g. full_name) and retrieve it as auth()->user()->full_name

    Read about

    Accessors - using it you can simply add computed properties:

    class User extends Authenticatable
    {
      public function getFullNameAttribute()
      {
         return "{$this->first_name} {$this->last_name}";
      }
    }

    reply
    0
  • Cancelreply