They do the same job, Just the "auth()" called a 'Helper function' and "Auth::" called facade
Difference between auth()->user()->id and Auth::user()->id
What's the difference between using:
auth()->user()->id
Auth::user()->id
Short explanation:
No difference really, they both return an instance of Illuminate\Auth\AuthManager.
So Auth:: and auth() in your examples will be the exact same object.
auth() is just a helper so you don't have to import the Facade, some people prefer the facade, some prefer the helper method.
Long explanation:
You can see this in action if you look in the source for Illuminate\Foundation\helpers.php, there you will see that the auth() merely resolves the AuthFactory interface.
function auth($guard = null)
{
if (is_null($guard)) {
return app(AuthFactory::class);
}
// ...
}
The Auth facade resolves the facade accessor 'auth', for which you can see the definition for in
Illuminate\Auth\AuthServiceProvioder,
$this->app->singleton('auth', function ($app) {
// ...
return new AuthManager($app); // AuthManager implements the AuthFactory interface
});
the auth() helper is useful in views as they are not classes, so to use the facade you also have to provide the full namespace
To get id of user you can also use
Auth:id();
or
auth()->id();
Documentation: https://laravel.com/docs/7.x/authentication#retrieving-the-authenticated-user
The auth() function returns an authenticator instance. You may use it instead of the Auth facade for convenience. https://laravel.com/docs/7.x/helpers#method-auth
What's the difference between using:
auth()->user()->id
Auth::user()->id
@andyandy Four characters. One is just accessing the currently authenticated user via a global helper function; the other is accessing the authenticated user using a facade class.
Personally, if I need to get the user in a controller action, I’ll grab the user from the request, not from a global helper or facade:
public function someAction(Request $request)
{
$user = $request->user();
}
They all do the same thing, though.
Please or to participate in this conversation.