Currently Authenticated User

Advanced Security - PHP Register/Login System Advanced Security - PHP Register/Login System / How-to Last updated on Updated  Jan 16, 2019

After the user is successfully authenticated, his unique ID is stored inside the session and it can be easily obtained like following:

// Id of currently authenticated user
$userId = ASSession::get('user_id');

This ID can be used anywhere inside the application where we need to get the id for the current user. However, just to make things easier, information for the currently authenticated user is stored inside the container, so you can easily get all the info about the user without having to manually fetch his info. More about it in the following section.

User Details

As mentioned, all details about currently authenticated user are stored inside the container and can be easily accessed from anywhere inside the application like this:

$user = app('current_user');

// $user is actually a stdClass object, and it contains 
// the following data
$user->id; // user's unique id
$user->email; // user's email address
$user->first_name; // user's first name
$user->last_name; // user's last name
$user->confirmed; // boolean - TRUE if user is confirmed, FALSE otherwise
$user->role; // name of user's role
$user->role_id; // role id
$user->phone; // user's phone number
$user->address; // user's address
$user->is_banned; // boolean - TRUE if user is banned, FALSE otherwise
$user->is_admin; // boolean - TRUE if user is admin (has "admin" role), FALSE otherwise
$user->last_login; // Date and time last login

The advantage of this approach is that you can access the current user anywhere inside the application, and it is smart enough to query the database only once, no matter how many times you call app('current_user').