PHPackages                             genesis-brain/laravel-excel-import-analysis - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. genesis-brain/laravel-excel-import-analysis

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

genesis-brain/laravel-excel-import-analysis
===========================================

A reusable Excel import analysis framework for Laravel with rules, severity levels, analysis DTOs, and modular import behavior.

v1.0.0(5mo ago)0871↓47.7%MITPHPPHP &gt;=8.3CI passing

Since Dec 12Pushed 5mo agoCompare

[ Source](https://github.com/Genesis-Brain/laravel-excel-import-analysis)[ Packagist](https://packagist.org/packages/genesis-brain/laravel-excel-import-analysis)[ RSS](/packages/genesis-brain-laravel-excel-import-analysis/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (2)Used By (0)

Genesis Brain Laravel Excel Imports Analysis
============================================

[](#genesis-brain-laravel-excel-imports-analysis)

A reusable, rule-based Excel import analysis framework for Laravel. It provides structured per-row analysis, severity levels, contextual DTOs, and a clean import architecture that integrates seamlessly with **Laravel Excel**.

This package is designed to help you build **robust, extensible, and maintainable Excel import pipelines** in your Laravel applications.

✨ Features
----------

[](#-features)

- 🧩 Rule-based per-row validation
- ⚠️ Built-in severity levels (`INFO`, `WARNING`, `ERROR`, `CRITICAL`)
- 📄 Rich DTOs (messages, codes, row/column/cell, context)
- 🏗 Pluggable rules via repository
- ♻️ Reusable import architecture using traits &amp; contracts
- 📚 Clean interfaces and abstract base classes
- 🔌 Fully compatible with [Maatwebsite/Laravel-Excel](https://laravel-excel.com)

📦 Installation
--------------

[](#-installation)

```
composer require genesis-brain/laravel-excel-import-analysis
```

Requires:

- PHP &gt;= 8.2
- Laravel &gt;= 10
- maatwebsite/excel &gt;= 3.1

🚀 Basic Usage
-------------

[](#-basic-usage)

### 1. Create an Import

[](#1-create-an-import)

```
use Gbrain\ExcelImports\Concerns\AnalyzesData\AnalyzesData;
use Gbrain\ExcelImports\Contracts\ExcelImportAnalyzesDataInterface;
use Gbrain\ExcelImports\Enums\ExcelImportAnalysisLevelEnum;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ProductsImport implements ExcelImportAnalyzesDataInterface, WithHeadingRow
{
    use AnalyzesData;

    /**
     * Business logic that runs once a row has passed validation.
     */
    protected function handleRowImport(Collection $row): void
    {
        // Persist the row, dispatch a job, etc.
    }

    /**
     * Register the analysis rules for this import.
     *
     * @return list
     */
    public function getRulesCollection(): iterable
    {
        return [
            \Gbrain\ExcelImports\Abstracts\Analysis\ExampleRules\TitleIsRequiredImportRule::class,
            // Your custom rules...
        ];
    }

    /**
     * Minimal analysis level that should be considered an error for this import.
     */
    public function getMinimalReportLevel(): ExcelImportAnalysisLevelEnum
    {
        return ExcelImportAnalysisLevelEnum::WARNING;
    }
}
```

### 2. Run the Import

[](#2-run-the-import)

```
use Maatwebsite\Excel\Facades\Excel;

Excel::import(new ProductsImport(), 'products.xlsx');
```

If any analysis results are produced at or below the configured minimal level, an `Gbrain\ExcelImports\Exceptions\ExcelImportNotPassedRulesValidation` exception will be thrown. You can catch it to surface errors to users or logs.

```
try {
    Excel::import(new ProductsImport(), 'products.xlsx');
} catch (\Gbrain\ExcelImports\Exceptions\ExcelImportNotPassedRulesValidation $e) {
    foreach ($e->getAnalysisCollection() as $result) {
        // $result is an ExcelImportAnalysisResultDto
        // e.g. $result->message, $result->uniqueCode, $result->rowIndex, etc.
    }
}
```

🔍 Controlling Analysis Execution: `withAnalysis()` and `withoutAnalysis()`
--------------------------------------------------------------------------

[](#-controlling-analysis-execution-withanalysis-and-withoutanalysis)

The `AnalyzesData` trait provides two important methods to control **when analysis rules run** during an import:

### \### ✅ `withAnalysis(bool $withoutImport = false)` (default behaviour)

[](#--withanalysisbool-withoutimport--false-default-behaviour)

Enables analysis and allows you to decide whether the import should also run.

Since `$onlyAnalysis` is **false by default**, calling `withAnalysis()` without arguments means:

➡ **Analysis runs**➡ **Import also runs (if analysis passes)**

You may optionally pass a boolean:

```
$import->withAnalysis(false); // analysis + import
$import->withAnalysis(true);  // analysis only (no import)
```

- `withAnalysis(false)` → normal mode: validate rows *and* import if valid
- `withAnalysis(true)` → analysis-only mode: validate rows, skip import entirely

Example (normal mode):

```
Excel::import((new ProductsImport())->withAnalysis(), 'products.xlsx'); // default state
```

- Each row is validated using your registered rules
- All analysis results are collected
- If any rule produces a result at or below the minimal report level, an exception is thrown

### \### ⛔ `withoutAnalysis()`

[](#--withoutanalysis)

Disables all rule checks.

Use this when you want to:

- Import data **without validation**
- Re-run an import using only the business logic (`handleRowImport()`)
- Bypass rules temporarily (e.g. admin override)

Example:

```
Excel::import((new ProductsImport())->withoutAnalysis(), 'products.xlsx');
```

### \### 🔄 How it works internally

[](#--how-it-works-internally)

`withAnalysis()` and `withoutAnalysis()` work together using two internal flags:

- `$analyzeBeforeHandle` — whether rules should run at all
- `$onlyAnalysis` — whether **only** rules should run (skipping import)

According to the current implementation:

### ✔ Default state

[](#-default-state)

- `$analyzeBeforeHandle = true`
- `$onlyAnalysis = false`

So calling `withAnalysis()` with **no arguments**:

- enables analysis
- **does NOT** skip import

### ✔ Truth table

[](#-truth-table)

Method call`$analyzeBeforeHandle``$onlyAnalysis`Effect`withAnalysis()``true``false`Run analysis **and then import**`withAnalysis(false)``true``false`Same as above`withAnalysis(true)``true``true`Run analysis **only**, no import`withoutAnalysis()``false``false`Skip analysis, run import only### ✔ What actually happens

[](#-what-actually-happens)

- If **analysis is enabled** (`$analyzeBeforeHandle = true`), rules run on each row.
- If **minimal report level is breached**, an exception is thrown.
- If **only analysis** is enabled (`$onlyAnalysis = true`), the import is **skipped entirely**.
- If **withoutAnalysis()** is called, rules are skipped and only import logic runs.

### Summary

[](#summary)

- **withAnalysis()** → analysis + import (default)
- **withAnalysis(true)** → analysis only
- **withAnalysis(false)** → analysis + import
- **withoutAnalysis()** → import only

This gives you full control over whether to run validation-only scans, full validated imports, or unvalidated imports.\*\*, without changing your import class.

🧪 Writing Custom Rules
----------------------

[](#-writing-custom-rules)

Rules extend the abstract `ExcelImportAnalysisRule` and return an `ExcelImportAnalysisResultDto` when the rule fails.

```
use Gbrain\ExcelImports\Abstracts\Analysis\ExcelImportAnalysisRule;
use Gbrain\ExcelImports\Dtos\ExcelImportAnalysisResultDto;
use Illuminate\Support\Collection;

class PositiveQuantityRule extends ExcelImportAnalysisRule
{
    protected function getRowAnalysis(Collection $row, int $rowIndex): ?ExcelImportAnalysisResultDto
    {
        $qty = (int) ($row->get('quantity') ?? 0);

        if ($qty  $qty],
            );
        }

        return null;
    }
}
```

Then register it in your import’s `getRulesCollection()` method.

📊 Severity Levels
-----------------

[](#-severity-levels)

The package ships with a built-in severity enum:

```
use Gbrain\ExcelImports\Enums\ExcelImportAnalysisLevelEnum;

ExcelImportAnalysisLevelEnum::INFO;
ExcelImportAnalysisLevelEnum::WARNING;
ExcelImportAnalysisLevelEnum::ERROR;
ExcelImportAnalysisLevelEnum::CRITICAL;
```

Levels are comparable using helper methods:

```
$level->gte(ExcelImportAnalysisLevelEnum::WARNING);
$level->lt(ExcelImportAnalysisLevelEnum::ERROR);
```

Internally, comparison is driven by PHP 8 attributes (`ComparableValue`) attached to each enum case.

🧱 Architecture Overview
-----------------------

[](#-architecture-overview)

- **Contracts** — describe import, rule, and repository responsibilities
- **Abstracts** — provide base behavior (rules, repository)
- **Concerns** — traits that orchestrate analysis (`AnalyzesData`)
- **Enums** — severity levels, with comparable semantics
- **DTOs** — carry structured analysis results
- **Exceptions** — encapsulate failed analysis and structured context

🧪 Testing
---------

[](#-testing)

This package is designed to be test-friendly. Example Pest tests:

```
use Gbrain\ExcelImports\Abstracts\Analysis\ExampleRules\TitleIsRequiredImportRule;
use Gbrain\ExcelImports\Dtos\ExcelImportAnalysisResultDto;

test('TitleIsRequiredImportRule flags missing title', function () {
    $rule = new TitleIsRequiredImportRule();

    $result = $rule->validateRow(collect(['title' => null]), 0);

    expect($result)->toBeInstanceOf(ExcelImportAnalysisResultDto::class)
        ->and($result->uniqueCode)->toBe('no-title')
        ->and($result->level->name)->toBe('CRITICAL');
});
```

Run tests with:

```
vendor/bin/pest
```

📄 License
---------

[](#-license)

MIT

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance72

Regular maintenance activity

Popularity19

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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

Unknown

Total

1

Last Release

157d ago

### Community

Maintainers

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

---

Top Contributors

[![jojeringnax](https://avatars.githubusercontent.com/u/22145233?v=4)](https://github.com/jojeringnax "jojeringnax (9 commits)")

###  Code Quality

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/genesis-brain-laravel-excel-import-analysis/health.svg)

```
[![Health](https://phpackages.com/badges/genesis-brain-laravel-excel-import-analysis/health.svg)](https://phpackages.com/packages/genesis-brain-laravel-excel-import-analysis)
```

###  Alternatives

[wireui/wireui

TallStack components

1.8k1.3M16](/packages/wireui-wireui)[livewire/volt

An elegantly crafted functional API for Laravel Livewire.

4195.3M84](/packages/livewire-volt)[ramonrietdijk/livewire-tables

Dynamic tables for models with Laravel Livewire

21147.4k](/packages/ramonrietdijk-livewire-tables)[ronasit/laravel-helpers

Provided helpers function and some helper class.

1475.7k13](/packages/ronasit-laravel-helpers)[team-nifty-gmbh/tall-datatables

A package to create datatables using alpinejs, tailwind, livewire and laravel

1217.2k1](/packages/team-nifty-gmbh-tall-datatables)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

116.6k](/packages/tomshaw-electricgrid)

PHPackages © 2026

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