UserAccessLogService.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace App\Services;
  3. use App\Models\UserAccessLog;
  4. use Illuminate\Pagination\LengthAwarePaginator;
  5. class UserAccessLogService
  6. {
  7. public function getAllPaginated(array $filters = [], int $perPage = 10): LengthAwarePaginator
  8. {
  9. $query = UserAccessLog::with(['user:id,name,type'])
  10. ->orderBy('accessed_at', 'desc');
  11. if (!empty($filters['last_per_user'])) {
  12. $query->whereIn('id', function ($sub) {
  13. $sub->selectRaw('MAX(id)')
  14. ->from('users_access_logs')
  15. ->groupBy('user_id');
  16. });
  17. }
  18. if (!empty($filters['type'])) {
  19. $query->whereHas('user', fn($q) => $q->where('type', $filters['type']));
  20. }
  21. if (!empty($filters['date_from'])) {
  22. $query->whereDate('accessed_at', '>=', $filters['date_from']);
  23. }
  24. if (!empty($filters['date_to'])) {
  25. $query->whereDate('accessed_at', '<=', $filters['date_to']);
  26. }
  27. return $query->paginate($perPage);
  28. }
  29. }