useSanctum()
useSanctum()
is the primary composable for managing authentication within your application. It consolidates various authentication-related functionalities, including logging in, logging out, and accessing the current authenticated user.
Properties
options
This computed property gives you access to the module's configuration options, such as API endpoints and other settings. It mirrors the output ofuseSanctumOptions()
but is conveniently accessible withinuseSanctum()
.user
Theuser
property holds the data of the currently authenticated user. This property is reactive, meaning any changes to the user's state (e.g., login or logout) are automatically reflected in your application. It also supports typed user.Example:
javascriptinterface User { id: number; email: string; name: string; } const { user } = useSanctum<User>();
isLoggedIn
A boolean property that indicates whether a user is currently authenticated. It returnstrue
if the user is logged in andfalse
otherwise.
Methods
login(credentials)
This method is used to authenticate a user with the given credentials. Thecredentials
argument should be an object containing the necessary fields, such asemail
andpassword
, as required by your Laravel backend.Upon successful login, the
user
property is updated with the authenticated user's data, and theisLoggedIn
flag is set totrue
.Example:
javascriptconst { login } = useSanctum(); const userCredentials = { email: 'user@mail.com', password: '123123', }; await login(userCredentials);
logout()
:
This method logs out the authenticated user. It clears the user data, sets theisLoggedIn
flag tofalse
, and ensures the user's session is terminated on the backend.Example:
javascriptconst { logout } = useSanctum(); await logout();
refreshUser()
:
This method lets you manually refresh the current user's data by re-fetching it from the backend. It is handy in scenarios where the user's information might have changed without a full reload of the application.Example:
javascriptconst { refreshUser } = useSanctum(); await refreshUser();