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

Kikismedia's avatar

How to give user point for daily Login

I am creatint a daily Login, that's checks if user has login for that day and give user point, user on get point once for that day in my user table I have last_login field , and I am using global middleware for easy check, but I noticed user get point any time they logout and login back

class DailyLogin
{
    public function handle(Request $request, Closure $next)
    {
        $user = Auth::user();
        $today = Carbon::today();
        $yesterday = $today->subDay();

        $user->last_login = $today;
        $user->save();

        if ($user && $user->last_login >= $yesterday) {
            // User has logged in within the last 24 hours, do not give them a point
        } else {
            // User has not logged in within the last 24 hours, give them a point
            $user->points += 1;
            $user->save();
        }

        return $next($request);
    }
}
0 likes
8 replies
Snapey's avatar
Snapey
Best Answer
Level 122

reorganise and simplify

    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && $user->last_login < today()) {
            Auth::user()->increment('points');
            Auth::user()->last_login = today();
            Auth::user()->save();
        }

        return $next($request);
    }
3 likes
Kikismedia's avatar

@Snapey @jascha will user get point the next day or after 24hours has passed, because I want user to get paid the next day (new day) ,

Snapey's avatar

@Kikismedia Do you not understand the logic?

  • If the user is logged in, and they have not previously logged in today:
    • give them a point
    • set their last login to today

tomorrow is a new day so the first access (only) will give a point

The logic only considers the date. It is not based on elapsed hours

ramynagy's avatar

@Snapey Good but i think will great in listener for Illuminate\Auth\Events\Login event It will fire only when login What do you think 🤔

Snapey's avatar

@ramynagy yes, not forgetting to also account for remember me logins.

You would miss people that are logged in continuously over midnight.

Besides, we were asked to review the middleware

jascha's avatar

In the beginning of the method you're overwriting the information of the last login. Carbon has a method to check if a date is today. I would use this and after the check update the user:

class DailyLogin
{
    public function handle(Request $request, Closure $next)
    {
        $user = Auth::user();

		if (! $user->last_login->isToday()) {
				$user->points += 1;
            	$user->save();
		}


		$user->last_login = $today;
        $user->save();
       
        return $next($request);
    }
}

Please or to participate in this conversation.