How to add new value to "auth()" function after login?
P粉354948724
P粉354948724 2023-09-03 13:18:05
0
1
327
<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粉354948724
P粉354948724

reply all(1)
P粉351138462

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}";
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!