Search code examples
codeignitercodeigniter-4

How to display the session 'username' value of the logged-in User using the 'codeigniter4/shield' framework for CodeIgniter 4


I'm new to CodeIgniter and I installed the codeigniter4/shield authentication and authorization framework for CodeIgniter 4.

I need the session data of the logged-in User such as username, and email.

How can I get it?

What I've tried so far.

$item = $session->get('item');
$name = $_SESSION['name'];

Solution

  • Solution:

    Get logged-in username:

    auth()->user()->username;
    

    Get logged-in User email:

    auth()->user()->getEmail();
    

    Get the 'date & time' when the logged-in User account was created:

    auth()->user()->created_at->toDateTimeString();
    

    Get all logged-in User data.

    auth()->user()->toRawArray();
    

    Reference:

    Auth Helper

    The auth functionality is designed to be used with the auth_helper that comes with Shield. This helper method provides the auth() command which returns a convenient interface to the most frequently used functionality within the auth libraries. This must be loaded before it can be used.

    // get the current user
    auth()->user();
    
    // get the current user's id
    auth()->id();
    // or
    user_id();