检查用户是否使用laravel模型联机,将值返回到vue

qojgxg4l  于 2022-11-17  发布在  Vue.js
关注(0)|答案(1)|浏览(96)

我已经创建了一个中间件,我在其中检查用户状态(online,ofline)。

public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $expiresAt = now()->addMinutes(1); // keep online for 1 min 
            Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
  
            // Update on db last_online_at with now time
            User::where('id', Auth::user()->id)->update(['last_online_at' => now()]);
        }

        return $next($request);
    }

所以更新也和last_online_at clumn上的数据库。但我试图做的是看到前端的状态在线或离线。我已经创建了一个模型的方法

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

但我不知道如何在vue表上传递isOnline

<td>
     <span class="badge badge-warning">{{user.last_online_at}}</span>
 </td>
 <td>
   <span class="badge badge-success">Online</span>
   <span class="badge badge-danger">Offline</span>
 </td>

methods: {
  axios.post('/admin/users/getusers?page=' + this.pagination.current_page, {
                    perPage: this.displayRecord
                })
                .then(response => {
                    this.users = response.data.data
}

        computed: {

            getOnlineStatus() {
                var onlineUser = '';
                var now = new Date();
                this.users.forEach(function(user) {
                    onlineUser.push(user.last_online_at)
                })
                console.log(onlineUser);

                if(now == onlineUser) {
                    // want to print true or false i think
                }
            }

        },

n.拉瑞韦尔控制器

public function getUsers(Request $request)
    {
        abort_if(Gate::denies('user_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $paginate = $request->perPage;

        return new UserResource(User::paginate($paginate));
    }
cotxawn7

cotxawn71#

我还没有测试过这个,但应该是这样的。

<td>
     <span class="badge badge-warning">{{user.last_online_at}}</span>
 </td>
 <td>
   <span v-if="getOnlineStatus(user.last_online_at)" class="badge badge-success">Online</span>
   <span v-else class="badge badge-danger">Offline</span>
 </td>

methods: {
  ...someMethods,
 getOnlineStatus(testDate) {
                var myDate = new Date(testDate);
                var now = new Date();
                let FIVE_MINS = 60 * 5;
                return ((now - myDate) < FIVE_MINS);

            
            }
}

相关问题