How to add new value to "auth()" function after login?
P粉354948724
2023-09-03 13:18:05
<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>
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
With this default Laravel configuration, you get:
web
web
The guard provider (providingAuthenticatable
) isusers
users
The provider provides App\Models\User::classAuthenticatable
ContractThen, by calling
auth()->user()
- you will get an instance of App\Models\User::class or nullAnswer your question
You can add anything to the User model (e.g.
Read aboutfull_name
) and retrieve it asauth()->user()->full_name
Accessors - using it you can simply add computed properties: