Last active
November 2, 2022 19:48
-
-
Save whoisthisstud/5d57a678974681a1305fab7142408a3f to your computer and use it in GitHub Desktop.
HasOnlineStatus feature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Include the UserOnline::class in the $middlewareGroups array. | |
| /** | |
| * The application's route middleware groups. | |
| * | |
| * @var array<string, array<int, class-string|string>> | |
| */ | |
| protected $middlewareGroups = [ | |
| 'web' => [ | |
| \App\Http\Middleware\EncryptCookies::class, | |
| \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, | |
| \Illuminate\Session\Middleware\StartSession::class, | |
| \Illuminate\View\Middleware\ShareErrorsFromSession::class, | |
| \App\Http\Middleware\VerifyCsrfToken::class, | |
| \Illuminate\Routing\Middleware\SubstituteBindings::class, | |
| \App\Http\Middleware\UserOnline::class, // <----- HERE ----- | |
| ], | |
| 'api' => [ | |
| // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, | |
| 'throttle:api', | |
| \Illuminate\Routing\Middleware\SubstituteBindings::class, | |
| ], | |
| ]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Traits\User; | |
| use Cache; | |
| trait HasOnlineStatus | |
| { | |
| public function isCurrentlyOnline() | |
| { | |
| // Cache set to one minute, in App\Http\Middleware\UserOnline | |
| return Cache::has( 'user-is-online-' . $this->id ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Middleware; | |
| use Auth; | |
| use Cache; | |
| use Closure; | |
| use Carbon\Carbon; | |
| use Illuminate\Http\Request; | |
| class UserOnline | |
| { | |
| /** | |
| * Handle an incoming request. | |
| * | |
| * @param \Illuminate\Http\Request $request | |
| * @param \Closure $next | |
| * @return mixed | |
| */ | |
| public function handle(Request $request, Closure $next) | |
| { | |
| if( Auth::check() ) { | |
| $expires_at = Carbon::now()->addMinutes(1); // Expires in one minute | |
| Cache::put('user-is-online-' . Auth::user()->id, true, $expires_at ); | |
| } | |
| return $next($request); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment