Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

Session variable not fetching in listener

I am try to store login activity along with user timezone i have code like below,

in login page i have used below jquery cdn,

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data.min.js" crossorigin="anonymous"></script>

i have input field with hidden type like below and script to append client timezone,

  <input type="hidden" name="timezone" id="timezone">
<script>
  var timezone = moment.tz.guess();
  $('#timezone').val(timezone);
</script>

i have login code like below. i set timezone in session.

public function postAdminLoginPage(Request $request)
      {
        
        request()->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

          $credential = [
            'email' => request('email'),
            'password' => request('password'),
            'role_id' => 1
          ];

        $remember_me  = ( !empty( $request->remember_me ) )? true : false;

        if(Auth::attempt($credential,$remember_me)){
            session(['timezone' => $request->timezone]); // saving to session

            return redirect('admin/dashboard');
        } else {
          return redirect('adminlogin')->withErrors('Email/Password is wrong. try again');
        }
      }

Now after login i am storing login activity in login_activities table

i have table like below,

login_activities

id, user_id, ip, user_agent, timezone

EventServiceProvider.php

'Illuminate\Auth\Events\Login' => [
        'App\Listeners\LogSuccessfulLogin',
    ],

inside Listeners i have file called, LogSuccessfulLogin.php

public function handle(Login $event)
    {
        //
        LoginActivity::create([
          'user_id'       =>  $event->user->id,
          'user_agent'    =>  \Illuminate\Support\Facades\Request::header('User-Agent'),
          'ip_address'    =>  \Illuminate\Support\Facades\Request::ip(),
          'timezone'      =>  getTimezone(),
        ]);
    }

In helper.php i hav function like below,

function getTimezone()
{
  return (Session::has('timezone') ? Session::get('timezone') : 'UTC');
}

But i am not able to fetch the session variable in listeneres. if i test in seperate route it is displaying properly. may be it will take one refresh. how to this session variable to listers so that i will store in activity to display the last login date based on timezone.

0 likes
4 replies
bobbybouwmann's avatar

The listener is not part of the session. You could queue a listener for later execution so you can't rely on the session.

Instead, you should set the timezone for the event. Since this is a Laravel event that's not easily done. Another option is storing the timezone on the user instead.

Snapey's avatar

try

session()->save()

after setting it, since session is only saved by terminable middleware.

Your listener cannot be queued for this to work since it would then not be part of the same request cycle.

A couple of other tips. The session::get command accepts a default value incase the session is not set

function getTimezone()
{
  return session()->get('timezone','UTC');
}

but then of course you would not need the function at all

You can use $request->has for your checkboxes

        $remember_me  = $request->has('remember_me');

since only checked checkboxes will be part of the form posting. Again, you could lose the temporary variable

    if(Auth::attempt($credential,$request->has('remember_me'))){

By ditching the built in auth scaffolding you may have removed login throttling which is not a good idea

Deekshith's avatar

@snapey Thank you for the suggestions it reduced some functions.

and i have altered code like below,

session(['timezone' => $request->timezone]); // saving to session
session()->save();

But still it is not taking and can i do like this?

creating timezone column in user table and whenever user logged in update the timezone column of user and later in listener fetch the timezone from column instead of session?

also if i store created_at in LoginActivity in UTC format and i want to display the last created_at date based on user timezone. i tried to set timezone dynamically using helper during fetch but it is not working.

function getLastLoginTime()
{
	$timezone = !is_null($event->user->timezone) ? $event->user->timezone : 'UTC';
     config(['app.timezone' => $timezone]);
      date_default_timezone_set($timezone);
  $user_id = Auth::user()->id;
  $getLatestLogin = LoginActivity::where('user_id',$user_id)->orderBy('id','DESC')->first();
  return $getLatestLogin;
}

Snapey's avatar

Do you think the user changes timezone after registering?

I would capture the timezone on the register page, and then show it on the user profile page for them to change if you got it wrong or they were away from home when they registered.

In your view of the login time, get it as UTC and then convert it in the view. This is an example I use;

{{ $election->election_start_date->setTimezone($user->timezone)->format('Y-m-d H:i') }}

The start_date is a Carbon instance. Apply the timezone then format the value.

Please or to participate in this conversation.