How laravel `Auth:user()` or `Auth:id()` works
Solution 1
Did you read this? Its a good guide to start with
https://laravel.com/docs/5.4/authentication
Solution 2
Here's my attempt at figuring out what actually happens on an Auth::user()
call:
Auth::user()
Illuminate\Support\Facades\Auth
extends Illuminate\Support\Facades\Facade
Facade::__callStatic('user')
static::getFacadeRoot()
resolveFacadeInstance(static::getFacadeAccessor == 'auth' (from Auth class))
return static::$app[$name];
static::$app is instance of Illuminate\Foundation\Application
extends Illuminate\Container\Container
which implements ArrayAccess
(which is why $obj[]
syntax works)
Container::offsetGet(auth)
Application::make(auth)
Container::getAlias(auth) return 'auth'
Container::make(auth)
Container::resolve(auth)
yadda, yadda, yadda
See in Application::registerCoreContainerAliases
'auth' = Illuminate\Auth\AuthManager
AuthManager::user() = AuthManager::__call = $this->guard()->user()
AuthManager::guard(web)
AuthManager::resolve(web) (see config/auth.php)
AuthManager::createSessionDriver() returns new Illuminate\Auth\SessionGuard
SessionGuard::user() // <---- this is what actually get's called, based on default config
Solution 3
You can find this method in Auth\SessionGuard class :
Authenticatable|null user()
Get the currently authenticated user.
Return Value Authenticatable|null
Check it out: https://laravel.com/api/5.7/Illuminate/Auth/SessionGuard.html#method_user
Solution 4
laravel uses session for authentication.if you are beginer in laravel then must read following link:
https://laravel.com/docs/5.4/authentication
i think its help you
Related videos on Youtube
GRESPL Nagpur
Updated on June 04, 2022Comments
-
GRESPL Nagpur almost 2 years
How laravel
Auth:user()
orAuth:id()
worksIs it resides in session or database.
I searched but not get good article.
Please help to understand. I know I will get many down-votes ;)
-
Rob about 6 yearsThis doesn't really answer the question of "how". When I look at that class (vendor/laravel/framework/src/Illuminate/Support/Facades/Auth.php) it has two methods, neither of which are user(), and extends an abstract class (Facade) that likewise doesn't have a user() method. And I don't see how the __callStatic method would do anything outside of those two classes either. HOW exactly does Auth::user() work?
-
fignet almost 3 yearsI had this question too and this answer really helped. I needed to figure out whether
Auth::user()
andAuth::id()
retrieved the details from the database or session. From reading the source ofSessionGuard::user()
andSessionGuard::id()
it appears: 1. The value is reused from memory if this call has been made previously within the current request. 2. The value is called from the proper provider (Which is often the db) if it is not currently in memory. 3. ForAuth::id
the value is exclusively pulled from the Session. Note that if you use the DB for sessions this is irrelevant.