PHPackages                             makaveli/laravel-login-history - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. makaveli/laravel-login-history

ActiveLibrary[Framework](/categories/framework)

makaveli/laravel-login-history
==============================

Advanced Login History for Laravel

1.1.5(1mo ago)0101MITPHPPHP ^8.2

Since Jul 20Pushed 1mo agoCompare

[ Source](https://github.com/Ma1kaveli/laravel-login-history)[ Packagist](https://packagist.org/packages/makaveli/laravel-login-history)[ RSS](/packages/makaveli-laravel-login-history/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (6)Versions (15)Used By (1)

makaveli/laravel-login-history
==============================

[](#makavelilaravel-login-history)

[![Packagist Version](https://camo.githubusercontent.com/46e109c378f8103fafc4963fc480190e21dff5d18d1a79bb794734f4a57a9437/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616b6176656c692f6c61726176656c2d6c6f67696e2d686973746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-login-history)[![Packagist Downloads](https://camo.githubusercontent.com/dbf97927da7c3ffc2ce1cec6fb7baf34ee2f282866a45aaefed684342de8928a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616b6176656c692f6c61726176656c2d6c6f67696e2d686973746f72792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/makaveli/laravel-login-history)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

🌍 Languages
-----------

[](#-languages)

- 🇺🇸 English (default)
- 🇷🇺 [Русская версия](docs/ru/README.md)

Table of Contents
-----------------

[](#table-of-contents)

1. [Introduction](#introduction)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Core Components](#core-components)
    - [LoginHistory Trait](#loginhistory-trait)
    - [UserLoginHistoryActions](#userloginhistoryactions)
    - [UserLoginHistoryRepository](#userloginhistoryrepository)
    - [UserLoginHistoryListDTO](#userloginhistorylistdto)
    - [Filters](#filters)
    - [Resources](#resources)
    - [Console Commands](#console-commands)
6. [Database Schema](#database-schema)
7. [Quick Start](#quick-start)
8. [Integration with BaseRepository](#integration-with-baserepository)
9. [Extending the Package](#extending-the-package)
10. [Recommendations](#recommendations)
11. [Useful Links](#useful-links)

Introduction
------------

[](#introduction)

**makaveli/laravel-login-history** is a Laravel package that provides advanced logging of user authentication events. It records the user ID and a fingerprint – structured data about the session or device used to log in. The package supports asynchronous logging via queues, flexible filtering, pagination, and integrates seamlessly with `makaveli/laravel-core` and `makaveli/laravel-query-builder`.

Key features:

- Recording login history with user binding and arbitrary JSON fingerprint.
- Asynchronous logging through Laravel queues.
- Filtering and pagination of login history data.
- Console commands to generate test data and run migrations.
- Configurable support for roles and organizations (optional).
- Easy adaptation via filter transformers.

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 10.10, 11.0, or 12.0
- [makaveli/laravel-query-builder](https://github.com/Ma1kaveli/laravel-query-builder) (v1.1.4)
- [makaveli/laravel-logger](https://github.com/Ma1kaveli/laravel-logger) (v1.1.4)

Installation
------------

[](#installation)

1. Install the package via Composer:

    ```
    composer require makaveli/laravel-login-history
    ```
2. (Optional) Publish the configuration file to customize settings:

    ```
    php artisan vendor:publish --tag=login-history-config
    ```

    This will copy the configuration file to `config/login-history.php`.
3. Run the package migrations to create the history table:

    ```
    php artisan migrate:login-history
    ```

    This creates the `users.user_login_histories` table.

Configuration
-------------

[](#configuration)

The file `config/login-history.php` allows you to configure the following parameters:

ParameterDescriptionDefault`user_model`User model class`App\Models\User::class``search_filter_fields`Model fields to search via the `search` parameter`['name', 'patronymic', 'family_name', 'phone', 'email']``with_role`Whether the user model has a role relationship (affects role filtering)`true``with_organization`Whether the role model has an `organization_id` field (affects organization filtering)`true``advanced_filters`Callback for adding custom filters`null``user_login_history`Number of test records generated by the seeder`100``transformers`Array of functions to transform filter parameters`[]``user_resource`Resource class for formatting user data`[\App\Modules\Base\Resources\UserShortResource::class, 'once']`Example configuration:

```
return [
    'user_model' => App\Modules\Base\Models\User::class,
    'search_filter_fields' => ['name', 'patronymic', 'family_name', 'phone', 'email'],
    'with_role' => true,
    'advanced_filters' => function (\LoginHistory\Filters\UserLoginHistoryFilters $self) {
        $self->applyInteger('user_id');
    },
    'with_organization' => true,
    'user_login_history' => env('USER_LOGIN_HISTORY_FACTORY', 100),
    'transformers' => [
        'role_id' => [\App\Modules\Role\Helpers\TransformRoleFilter::class, 'getRealRoleIdFromListRequest'],
        'user_id' => [\App\Modules\User\Helpers\TransformUserFilter::class, 'getRealUserIdFromListRequest'],
        'organization_id' => [\App\Modules\Organization\Helpers\TransformOrganizationFilter::class, 'getRealOrganizationIdFromListRequest'],
    ],
    'user_resource' => [\App\Modules\Base\Resources\UserShortResource::class, 'once'],
];
```

Core Components
---------------

[](#core-components)

### LoginHistory Trait

[](#loginhistory-trait)

The trait is added to the controller or any class where authentication occurs. It provides two methods:

- `writeLoginHistory(Request $request, ?Authenticatable $user = null)`: Synchronous history record.
- `writeAsyncLoginHistory(Request $request, ?Authenticatable $user = null)`: Asynchronous record via queue.

```
use LoginHistory\Traits\LoginHistory;

class AuthController extends Controller
{
    use LoginHistory;

    public function login(Request $request)
    {
        // ... authentication ...
        $this->writeLoginHistory($request);
        // or $this->writeAsyncLoginHistory($request);
    }
}
```

If no user is explicitly passed, the method uses `auth()->user()`.

### UserLoginHistoryActions

[](#userloginhistoryactions)

An action class that encapsulates the history writing logic. Can be used without the trait:

```
$actions = new UserLoginHistoryActions();
$actions->writeToHistory($user, $request);
```

### UserLoginHistoryRepository

[](#userloginhistoryrepository)

The repository for working with the `UserLoginHistory` model. It extends `BaseRepository` from `makaveli/laravel-core` and adds a `getPaginatedList` method that accepts a `UserLoginHistoryListDTO` and returns a paginated result.

```
use LoginHistory\Repositories\UserLoginHistoryRepository;
use LoginHistory\DTO\UserLoginHistoryListDTO;

$repository = new UserLoginHistoryRepository();
$dto = UserLoginHistoryListDTO::fromRequest($request);
$paginator = $repository->getPaginatedList($dto);
```

### UserLoginHistoryListDTO

[](#userloginhistorylistdto)

A DTO for filtering the login history list. It extracts parameters from the request and applies transformers (if defined). Supported fields:

ParameterTypeDescription`dateFrom`stringStart date (Y-m-d)`dateTo`stringEnd date (Y-m-d)`roleId`intFilter by role ID (requires `with_role = true`)`userId`intFilter by user ID`organizationId`intFilter by organization ID (requires `with_role = true` and `with_organization = true`)`search`stringSearch across fields defined in `search_filter_fields`Transformers (functions in the config) allow modifying these parameter values based on the current user’s permissions.

### Filters

[](#filters)

The package uses `makaveli/laravel-query-builder`. The `UserLoginHistoryFilters` class (extends `BaseQueryBuilder`) applies filters based on the DTO. You can extend it via the `advanced_filters` configuration parameter by providing a callback.

Example of adding a custom filter:

```
'advanced_filters' => function (\LoginHistory\Filters\UserLoginHistoryFilters $self) {
    $self->applyInteger('user_id');
},
```

### Resources

[](#resources)

- `UserLoginHistoryResource`: Formats a single history record. By default it includes `id`, `fingerprint`, `created_at`, and the user formatted via `user_resource`.
- `PaginatedCollection` from `laravel-query-builder` is used for pagination.

### Console Commands

[](#console-commands)

CommandDescription`php artisan seed:test-user-login-histories`Creates test history records (count set by `user_login_history`)`php artisan migrate:login-history`Runs the package migrationsDatabase Schema
---------------

[](#database-schema)

The package creates the table `users.user_login_histories`:

ColumnTypeDescription`id`bigint (PK)Auto‑increment ID`user_id`bigint (FK)ID of the user who logged in`fingerprint`jsonbArbitrary session/device data`created_at`timestampLogin time`updated_at`timestampLast update timeQuick Start
-----------

[](#quick-start)

### 1. Configure the package (if needed)

[](#1-configure-the-package-if-needed)

Edit `config/login-history.php` – specify the correct user model, search fields, user resource, etc.

### 2. Add the trait to your authentication controller

[](#2-add-the-trait-to-your-authentication-controller)

```
use LoginHistory\Traits\LoginHistory;

class AuthController extends Controller
{
    use LoginHistory;

    public function login(Request $request)
    {
        // ... credentials check ...
        if (auth()->attempt($credentials)) {
            // Record history (synchronously)
            $this->writeLoginHistory($request);
            // or asynchronously:
            // $this->writeAsyncLoginHistory($request);
            return response()->json(['message' => 'Login successful']);
        }
        return response()->json(['message' => 'Invalid credentials'], 401);
    }
}
```

### 3. Retrieve the history list in a controller

[](#3-retrieve-the-history-list-in-a-controller)

```
use LoginHistory\Repositories\UserLoginHistoryRepository;
use LoginHistory\DTO\UserLoginHistoryListDTO;
use QueryBuilder\Resources\PaginatedCollection;
use LoginHistory\Resources\UserLoginHistoryResource;

class UserLoginHistoryController extends Controller
{
    public function index(Request $request)
    {
        $dto = UserLoginHistoryListDTO::fromRequest($request);

        $repository = new UserLoginHistoryRepository();

        $paginator = $repository->getPaginatedList($dto);

        return new PaginatedCollection(
            $paginator,
            UserLoginHistoryResource::collection($paginator)
        );
    }
}
```

Integration with BaseRepository
-------------------------------

[](#integration-with-baserepository)

`UserLoginHistoryRepository` already extends `BaseRepository`, so it can be used in a service provider or injected via the container. In a controller:

```
use LoginHistory\Repositories\UserLoginHistoryRepository;

class UserLoginHistoryController extends Controller
{
    public function __construct(
        private UserLoginHistoryRepository $repository
    ) {}

    public function index(Request $request)
    {
        $dto = UserLoginHistoryListDTO::fromRequest($request);

        $paginator = $this->repository->getPaginatedList($dto);

        return UserLoginHistoryResource::collection($paginator);
    }
}
```

The `getPaginatedList` method automatically applies the filters defined in the DTO and configuration.

Extending the Package
---------------------

[](#extending-the-package)

You can customize the package by overriding:

- **Model**: Extend `LoginHistory\Models\UserLoginHistory` and bind your own model in a service provider if necessary.
- **Filters**: Extend `UserLoginHistoryFilters` and override the `list()` method, or use `advanced_filters` to add custom conditions.
- **DTO**: Create your own DTO extending `UserLoginHistoryListDTO` and override `fromRequest`.
- **Resources**: Create your own resource class and use it in `UserLoginHistoryResource` (or directly in the controller).
- **Transformers**: Define functions in the configuration to transform the `role_id`, `user_id`, and `organization_id` parameters.

Recommendations
---------------

[](#recommendations)

- **Always configure `user_model`** according to your actual user model.
- **Use asynchronous logging** (`writeAsyncLoginHistory`) in production to avoid increasing response time.
- **Define transformers** if you need to restrict data access based on the user’s role.
- **Adjust the search fields** in `search_filter_fields` to match your user model.
- **When using roles and organizations**, ensure your user model has the corresponding relationships.
- **Add database indexes** on `user_id` and `created_at` for faster queries.

Useful Links
------------

[](#useful-links)

- Package repository:
- Dependencies:
    - [makaveli/laravel-query-builder](https://github.com/Ma1kaveli/laravel-query-builder)
    - [makaveli/laravel-logger](https://github.com/Ma1kaveli/laravel-logger)
    - [makaveli/laravel-core](https://github.com/Ma1kaveli/laravel-core)

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance91

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Total

14

Last Release

44d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ed91cef75c6ac70dbc36843a28453115d78996faf342c9d0f86d89283b751522?d=identicon)[Ma1kaveli](/maintainers/Ma1kaveli)

---

Top Contributors

[![Ma1kaveli](https://avatars.githubusercontent.com/u/74207027?v=4)](https://github.com/Ma1kaveli "Ma1kaveli (14 commits)")

---

Tags

frameworklaravel

### Embed Badge

![Health badge](/badges/makaveli-laravel-login-history/health.svg)

```
[![Health](https://phpackages.com/badges/makaveli-laravel-login-history/health.svg)](https://phpackages.com/packages/makaveli-laravel-login-history)
```

###  Alternatives

[codewithdennis/larament

Larament is a time-saving starter kit to quickly launch Laravel 13.x projects. It includes FilamentPHP 5.x pre-installed and configured, along with additional tools and features to streamline your development workflow.

3691.5k](/packages/codewithdennis-larament)[kompo/kompo

Laravel &amp; Vue.js FullStack Components for Rapid Application Development

11812.4k21](/packages/kompo-kompo)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
