Laravel 跟踪用户活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45592533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:28:39  来源:igfitidea点击:

Laravel Tracking user activity

laraveluser-activity

提问by brightniyonzima

Is there a way i can track a logged in user activity in Laravel without using any packages? I have tried using antonioribeiro/tracker package but doesn't have a clear read me manual. I want to know details like the pages visited by a user. PS: For a small project i usually create a simple logPageHit() function that i place on the necessary Controller methods but right now am dealing with a big project

有没有一种方法可以在不使用任何包的情况下跟踪 Laravel 中登录的用户活动?我曾尝试使用 antonioribeiro/tracker 包,但没有清晰的自述手册。我想知道用户访问的页面等详细信息。PS:对于一个小项目,我通常会创建一个简单的 logPageHit() 函数,我将它放在必要的 Controller 方法上,但现在我正在处理一个大项目

回答by AddWeb Solution Pvt Ltd

You could use a Log package with events,with example please follow this link

您可以使用带有事件的日志包,例如请点击此链接

ORLaravel Eloquent have many events for manageit

或者Laravel Eloquent 有很多事件来管理

Hope this work for you!!!

希望这对你有用!!!

回答by diakosavvasn

Tracking If a User Is Currently Online

跟踪用户当前是否在线

You can create a Middleware

您可以创建一个中间件

php artisan make:middleware LastUserActivity

Inside the handle method, we need to add the following code:

在handle方法中,我们需要添加如下代码:

if(Auth::check()) {
    $expiresAt = Carbon::now()->addMinutes(5);
    Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
}

Go to App\Http\Kernel.php

转到 App\Http\Kernel.php

add the above code, inside $middlewareGroups in the websection.

web部分的$middlewareGroups 中添加上面的代码。

 \App\Http\Middleware\LastUserActivity::class,

Note:It is important that it's added after the StartSession middleware, otherwise, the Auth facade will not have access to the logged in user.

注意:一定要在 StartSession 中间件之后添加,否则 Auth Facade 将无法访问已登录的用户。

Go to App\User.php and add this method.

转到 App\User.php 并添加此方法。

public function isOnline()
{
    return Cache::has('user-is-online-' . $this->id);
}

Now use this in any of your views.

现在在您的任何视图中使用它。

@if($user->isOnline())
    user is online!!
@endif

Hope it helps. Read thistutorial for more info.

希望能帮助到你。阅读教程了解更多信息。