PHPackages                             marventhieme/laravel-authorization-logger - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. marventhieme/laravel-authorization-logger

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

marventhieme/laravel-authorization-logger
=========================================

A Laravel package for logging authorization denials with user context, policy information, and configurable drivers (Ray, Database, Log).

0.3.0(2mo ago)0295MITPHPPHP ^8.2CI failing

Since Nov 30Pushed 2mo agoCompare

[ Source](https://github.com/marventhieme/laravel-authorization-logger)[ Packagist](https://packagist.org/packages/marventhieme/laravel-authorization-logger)[ Docs](https://github.com/marventhieme/laravel-authorization-logger)[ GitHub Sponsors]()[ RSS](/packages/marventhieme-laravel-authorization-logger/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (18)Versions (8)Used By (0)

Laravel Authorization Logger
============================

[](#laravel-authorization-logger)

[![Latest Version on Packagist](https://camo.githubusercontent.com/5f330144e2edef9eb0ccd196feea660be5e8ed917dbc161d05bd176942fb01de/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d617276656e746869656d652f6c61726176656c2d617574686f72697a6174696f6e2d6c6f676765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/marventhieme/laravel-authorization-logger)[![GitHub Tests Action Status](https://camo.githubusercontent.com/a26df4738099bc78766f902198a58a7b6abc2ccae6da897a22101c9d0ebda75e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d617276656e746869656d652f6c61726176656c2d617574686f72697a6174696f6e2d6c6f676765722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/marventhieme/laravel-authorization-logger/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/2ad59ff1435b684cede4dc6cd235cce56bc86b75c6742612b90d347b2f6eb0af/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d617276656e746869656d652f6c61726176656c2d617574686f72697a6174696f6e2d6c6f676765722f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/marventhieme/laravel-authorization-logger/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/464787059c9cdf6ef786b743070d89dd158b454ef525728533d4c30d3cbb85ae/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d617276656e746869656d652f6c61726176656c2d617574686f72697a6174696f6e2d6c6f676765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/marventhieme/laravel-authorization-logger)

A Laravel package that automatically logs authorization denials (failed `Gate::allows()` and policy checks) with comprehensive context including user information, policy details, request data, and the referrer URL. Perfect for security auditing, debugging authorization issues, and monitoring unauthorized access attempts.

Features
--------

[](#features)

- **Automatic Logging**: Hooks into Laravel's Gate system to automatically log all authorization denials
- **Rich Context**: Captures user, policy, and request information including:
    - User ID, IP address, and roles (Spatie Laravel Permission compatible)
    - Policy class, method, and ability being checked
    - Model class and ID (if applicable)
    - Request method, URL, endpoint, route name, and referrer
    - Sanitized request body with sensitive field filtering
- **Multiple Handlers**: Built-in handlers for Ray, Laravel Log, and Database storage
- **Flexible Configuration**: Fine-tune what gets logged and what gets ignored
- **Database Pruning**: Automatic cleanup of old logs with configurable retention periods
- **Security Focused**: Automatically filters sensitive fields like passwords and tokens
- **Custom Handlers**: Easy to create your own log handlers for any destination

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

[](#installation)

Install the package via Composer:

```
composer require marventhieme/laravel-authorization-logger
```

### Database Setup

[](#database-setup)

Publish and run the migrations:

```
php artisan vendor:publish --tag="laravel-authorization-logger-migrations"
php artisan migrate
```

This creates an `authorization_denials` table to store authorization denial logs.

### Configuration

[](#configuration)

Publish the config file:

```
php artisan vendor:publish --tag="laravel-authorization-logger-config"
```

This will create `config/authorization-logger.php` with the following options:

```
return [
    // Enable/disable logging globally
    'enabled' => env('AUTHORIZATION_LOGGING_ENABLED', true),

    // Log handlers pipeline - data flows through each handler
    'handlers' => [
        \MarvenThieme\LaravelAuthorizationLogger\Handlers\DebugToRay::class,
        \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToDatabase::class,
        // \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToLog::class,
    ],

    // HTTP methods to skip logging (e.g., ['GET', 'HEAD'])
    'http_methods_to_ignore' => [],

    // Classes to ignore in the stack trace
    'classes_to_ignore' => [
        \Illuminate\Http\Resources\Json\JsonResource::class,
    ],

    // Sensitive fields filtered from request bodies
    'sensitive_fields' => [
        'password', 'password_confirmation', 'token', 'api_token',
        'secret', 'private_key', 'card_number', 'cvv', 'ssn',
        // ... see config file for full list
    ],

    // Maximum request body size in bytes
    'max_body_size' => env('AUTHORIZATION_LOGGING_MAX_BODY_SIZE', 10240),

    // Log channel for WriteToLog handler
    'log_channel' => env('AUTHORIZATION_LOGGING_CHANNEL', 'daily'),

    'database' => [
        // Days to keep logs before pruning
        'prunable_after_days' => env('AUTHORIZATION_LOGGING_PRUNABLE_AFTER_DAYS', 30),
    ],
];
```

Usage
-----

[](#usage)

Once installed, the package works automatically. Any authorization denial will be logged according to your configuration.

### Example Scenarios

[](#example-scenarios)

**Policy denial:**

```
// In your controller
$this->authorize('update', $post); // Fails if user can't update

// Automatically logs:
// - User: ID, IP, roles
// - Policy: PostPolicy::update
// - Model: App\Models\Post #123
// - Request: POST /posts/123, referrer, body
```

**Gate denial:**

```
Gate::authorize('admin-only-feature'); // Fails for non-admins

// Automatically logs:
// - User: ID, IP, roles
// - Ability: admin-only-feature
// - Request: Current request context
```

### Available Handlers

[](#available-handlers)

#### DebugToRay

[](#debugtoray)

Sends authorization denials to [Ray](https://myray.app/) for real-time debugging.

```
'handlers' => [
    \MarvenThieme\LaravelAuthorizationLogger\Handlers\DebugToRay::class,
],
```

#### WriteToDatabase

[](#writetodatabase)

Stores denials in the `authorization_denials` table.

```
'handlers' => [
    \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToDatabase::class,
],
```

Query the database:

```
use MarvenThieme\LaravelAuthorizationLogger\Models\AuthorizationDenial;

// Recent denials for a user
$denials = AuthorizationDenial::where('user_id', $userId)
    ->orderBy('logged_at', 'desc')
    ->get();

// Denials for a specific ability
$denials = AuthorizationDenial::where('ability', 'update')
    ->where('model_class', Post::class)
    ->get();
```

#### WriteToLog

[](#writetolog)

Writes denials to Laravel's log system.

```
'handlers' => [
    \MarvenThieme\LaravelAuthorizationLogger\Handlers\WriteToLog::class,
],
```

Configure the log channel:

```
'log_channel' => env('AUTHORIZATION_LOGGING_CHANNEL', 'daily'),
```

### Creating Custom Handlers

[](#creating-custom-handlers)

Create your own handler by implementing the `LogHandler` contract:

```
namespace App\Handlers;

use MarvenThieme\LaravelAuthorizationLogger\Contracts\LogHandler;
use MarvenThieme\LaravelAuthorizationLogger\Objects\LogData;

class SendToSlack implements LogHandler
{
    public function handle(LogData $logData): void
    {
        // Send to Slack, email, external API, etc.
        // Access data: $logData->userContext, $logData->policyContext, $logData->requestContext
    }
}
```

Register it in config:

```
'handlers' => [
    \App\Handlers\SendToSlack::class,
],
```

### LogData Structure

[](#logdata-structure)

The `LogData` object passed to handlers contains:

```
// Event info
$logData->event;      // "Authorization Denied"
$logData->timestamp;  // ISO8601 timestamp

// User context
$logData->userContext->type;        // "authenticated" or "anonymous"
$logData->userContext->userId;      // User ID or null
$logData->userContext->ipAddress;   // IP address
$logData->userContext->roles;       // Array of role names (if using Spatie Permission)

// Policy context
$logData->policyContext->ability;       // "update", "delete", etc.
$logData->policyContext->policyClass;   // "App\Policies\PostPolicy"
$logData->policyContext->policyMethod;  // "update"
$logData->policyContext->modelClass;    // "App\Models\Post"
$logData->policyContext->modelId;       // 123

// Request context
$logData->requestContext->method;     // "POST"
$logData->requestContext->url;        // "https://example.com/posts/123"
$logData->requestContext->endpoint;   // "/posts/123"
$logData->requestContext->routeName;  // "posts.update"
$logData->requestContext->referrer;   // Previous URL or null
$logData->requestContext->body;       // Sanitized request body
```

Database Pruning
----------------

[](#database-pruning)

The package uses Laravel's model pruning to automatically clean up old logs. Configure retention in your config:

```
'database' => [
    'prunable_after_days' => env('AUTHORIZATION_LOGGING_PRUNABLE_AFTER_DAYS', 30),
],
```

Schedule the pruning command in `app/Console/Kernel.php`:

```
protected function schedule(Schedule $schedule)
{
    $schedule->command('model:prune')->daily();
}
```

Advanced Configuration
----------------------

[](#advanced-configuration)

### Ignoring Specific HTTP Methods

[](#ignoring-specific-http-methods)

Skip logging for GET requests (useful for reducing noise from UI checks):

```
'http_methods_to_ignore' => ['GET', 'HEAD'],
```

### Ignoring Specific Classes

[](#ignoring-specific-classes)

By default, authorization checks from JSON Resources are ignored:

```
'classes_to_ignore' => [
    \Illuminate\Http\Resources\Json\JsonResource::class,
    // Add your own classes here
],
```

### Custom Sensitive Fields

[](#custom-sensitive-fields)

Add your own fields to filter from request bodies:

```
'sensitive_fields' => [
    'password',
    'api_key',
    'your_custom_secret_field',
],
```

Environment Variables
---------------------

[](#environment-variables)

Available environment variables for quick configuration:

```
AUTHORIZATION_LOGGING_ENABLED=true
AUTHORIZATION_LOGGING_MAX_BODY_SIZE=10240
AUTHORIZATION_LOGGING_CHANNEL=daily
AUTHORIZATION_LOGGING_PRUNABLE_AFTER_DAYS=30
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Marven Thieme](https://github.com/marventhieme)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance85

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

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 ~23 days

Recently: every ~34 days

Total

7

Last Release

78d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2c4c102b81ef27c8c29f2a30fff2a9c86619d4c05f9128c5aa97bb94c991709a?d=identicon)[marventhieme](/maintainers/marventhieme)

---

Top Contributors

[![marventhieme](https://avatars.githubusercontent.com/u/53627227?v=4)](https://github.com/marventhieme "marventhieme (12 commits)")

---

Tags

laravelMarven Thiemelaravel-authorization-logger

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/marventhieme-laravel-authorization-logger/health.svg)

```
[![Health](https://phpackages.com/badges/marventhieme-laravel-authorization-logger/health.svg)](https://phpackages.com/packages/marventhieme-laravel-authorization-logger)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k102.4M1.4k](/packages/spatie-laravel-permission)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M164](/packages/spatie-laravel-health)[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M100](/packages/dedoc-scramble)[spatie/laravel-passkeys

Use passkeys in your Laravel app

471890.7k39](/packages/spatie-laravel-passkeys)[keepsuit/laravel-opentelemetry

OpenTelemetry integration for laravel

167558.4k1](/packages/keepsuit-laravel-opentelemetry)

PHPackages © 2026

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