PHPackages                             meita/reports-generator - 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. [PDF &amp; Document Generation](/categories/documents)
4. /
5. meita/reports-generator

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

meita/reports-generator
=======================

Dynamic, storable report generator for Laravel with reusable definitions and runtime parameters.

1.0.3(8mo ago)09MITPHPPHP ^8.1

Since Dec 16Pushed 8mo agoCompare

[ Source](https://github.com/EngMEita/reports-generator)[ Packagist](https://packagist.org/packages/meita/reports-generator)[ RSS](/packages/meita-reports-generator/feed)WikiDiscussions main Synced 1w ago

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

meita/reports-generator
=======================

[](#meitareports-generator)

Dynamic report generator for Laravel that stores report definitions (SQL + filters + options), runs them on demand with bindings, and returns ready-to-use collections/JSON. Includes CLI runner, Blade directive, caching, pagination, raw query support, exports (CSV/Excel/PDF/Word/print), and DataTables-ready output.

- **Namespace**: `Meita\ReportsGenerator`
- **Author**: Eng. Mohamed A. Eita (`maa1987@hotmail.com`)

Features
--------

[](#features)

- Store report definitions in the database (`name`, `slug`, `base_query`, `filters`, `options`, `cache_ttl`, `connection`, `is_active`).
- Run stored reports with runtime parameters or run raw SQL without persistence.
- Optional caching (per report or per call).
- Optional pagination (wraps the query with count + limit/offset).
- CLI command `php artisan reports:run` for quick checks/exports.
- Blade directive `@report('slug', [...])` returns JSON for quick embedding.
- Export helpers: CSV, print/HTML table, DataTables-ready array, Excel/PDF/Word (bundled).
- Extra formats: JSON:API payload, XML payload; styling options for Excel/PDF/Word exports (headers, colors, merged cells).
- Configurable table name, connection, cache store, and TTL.

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

[](#installation)

1. Add the package (if local path, adjust as needed): ```
    composer require meita/reports-generator
    ```
2. Publish config and migration: ```
    php artisan vendor:publish --provider="Meita\ReportsGenerator\ReportsGeneratorServiceProvider" --tag=config
    php artisan vendor:publish --provider="Meita\ReportsGenerator\ReportsGeneratorServiceProvider" --tag=migrations
    ```
3. Run the migration: ```
    php artisan migrate
    ```

Configuration (config/reports-generator.php)
--------------------------------------------

[](#configuration-configreports-generatorphp)

- `connection`: default DB connection for reports (nullable = app default).
- `cache_store`: cache store name (nullable = default cache).
- `cache_ttl`: default TTL in seconds (can be overridden per report or per call).
- `table`: table name for stored reports.

Database structure
------------------

[](#database-structure)

The `reports` table stores definitions:

- `name` (string), `slug` (unique), `description` (text, optional)
- `connection` (string, optional) to point to another DB connection
- `base_query` (text) — use named bindings like `:status`, `:from_date`
- `filters` (json, optional) — e.g. `{"status":{"default":"active"}}`
- `options` (json, optional) — e.g. `{"paginate":true,"per_page":25,"cache_ttl":300}`
- `cache_ttl` (int), `is_active` (bool)

### Creating a report (seeder/tinker)

[](#creating-a-report-seedertinker)

```
use Meita\ReportsGenerator\Models\Report;

Report::create([
    'name' => 'Employees by branch',
    'slug' => 'employees-by-branch',
    'description' => 'Active employees grouped by branch.',
    'base_query' =>  [
        'status' => ['default' => 'active'],
        'branch_id' => ['default' => null],
    ],
    'options' => [
        'paginate' => true,
        'per_page' => 25,
        'cache_ttl' => 300,
    ],
    'cache_ttl' => 0,
    'is_active' => true,
]);
```

Usage
-----

[](#usage)

### Run a stored report in code

[](#run-a-stored-report-in-code)

```
use Meita\ReportsGenerator\Facades\ReportsGenerator;

$result = ReportsGenerator::report('employees-by-branch')
    ->params([
        'status' => 'active',
        'branch_id' => 5,
    ])
    ->options([
        'paginate' => true,   // enable pagination
        'per_page' => 20,
        'cache_ttl' => 120,   // seconds
    ])
    ->run();

$rows = $result->rows;      // array of stdClass rows
$json = $result->toJson();  // JSON payload
```

### Run a raw query (no stored definition)

[](#run-a-raw-query-no-stored-definition)

```
$sales = ReportsGenerator::raw(
    query: 'select id, total, created_at from orders where status = :status',
    params: ['status' => 'paid'],
    options: ['cache_ttl' => 60]
);
```

### Blade directive (returns JSON string)

[](#blade-directive-returns-json-string)

```
@php($reportJson = @report('employees-by-branch', ['branch_id' => 2]))
{{ $reportJson }}
```

### Blade rendering example

[](#blade-rendering-example)

```
@php($report = ReportsGenerator::report('employees-by-branch')->params(['branch_id' => 2])->run())

            ID
            Name
            Branch

        @foreach($report->rows as $row)

                {{ $row->id }}
                {{ $row->name }}
                {{ $row->branch_name }}

        @endforeach

```

### CLI runner

[](#cli-runner)

```
php artisan reports:run employees-by-branch --params="status:active,branch_id:2" --format=json
```

- `--format=table` (default) prints a table.
- `--format=json` prints JSON.

Exports (CSV / HTML / DataTables / Excel / PDF / Word / Print)
--------------------------------------------------------------

[](#exports-csv--html--datatables--excel--pdf--word--print)

- كل التنسيقات مدمجة مع الباكچ:
    - CSV: `$result->toCsv()` returns string.
    - HTML table / print: `$result->toHtmlTable()` returns a `` string.
    - DataTables-ready array: `$result->toDataTables()` returns `data`, `recordsTotal`, `recordsFiltered`, `meta`.
    - JSON:API: `$result->toJsonApi('employee')` returns JSON:API-compliant array.
    - XML: `$result->toXml('report', 'row')` returns an XML string.
    - Excel: `$result->exporter()->toExcel('employees.xlsx', [...options])`
    - PDF: `$result->exporter()->toPdf('Title', $path = null, [...options])`
    - Word: `$result->exporter()->toWord('Title', $path = null, [...options])`

### Examples

[](#examples)

```
$result = ReportsGenerator::report('employees-by-branch')->params(['branch_id' => 2])->run();

// CSV
$csv = $result->toCsv();

// DataTables JSON
return response()->json($result->toDataTables());

// Print/HTML
echo $result->toHtmlTable('Employees');

// Excel download (needs maatwebsite/excel)
return $result->exporter()->toExcel('employees.xlsx', [
    'heading_style' => [
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => ['fillType' => 'solid', 'color' => ['rgb' => '007bff']],
    ],
    'merge_cells' => ['A1:C1'],
    'column_widths' => ['A' => 12, 'B' => 25, 'C' => 20],
]);

// PDF (needs dompdf/dompdf)
$pdfBinary = $result->exporter()->toPdf('Employees', null, [
    'orientation' => 'landscape',
    'paper' => 'a4',
    'css' => 'table{width:100%;border-collapse:collapse;}th,td{border:1px solid #ddd;padding:6px;}thead th{background:#222;color:#fff;}',
]); // or pass a path instead of null to save

// Word DOCX (needs phpoffice/phpword)
$docPath = $result->exporter()->toWord('Employees', storage_path('app/employees.docx'), [
    'table_style' => ['borderSize' => 6, 'borderColor' => '999999'],
    'header_cell_style' => ['bgColor' => '222222'],
    'header_font_style' => ['bold' => true, 'color' => 'FFFFFF'],
]);

// JSON:API payload
return response()->json($result->toJsonApi('employee'));

// XML payload
return response($result->toXml('employees', 'employee'), 200, ['Content-Type' => 'application/xml']);
```

Options and filters
-------------------

[](#options-and-filters)

- **params**: named bindings that match `:placeholder` values inside `base_query`.
- **filters (stored)**: if a param is not provided at runtime, the `default` value from `filters` is injected.
- **options**:
    - `paginate` (bool) — paginate the SQL result.
    - `per_page` (int) — items per page (default 15).
    - `page` (int) — current page (default from request or 1).
    - `cache_ttl` (int) — cache result in seconds (0 disables).
    - `connection` (string) — override DB connection for this run.

Caching
-------

[](#caching)

- Report definition has `cache_ttl`; you can override per call via `options(['cache_ttl' => 300])`.
- Cache key is built from `slug` + params hash.
- Configure cache store via `cache_store` in the config.

Pagination
----------

[](#pagination)

- Enable by setting `options['paginate'] = true` on the report or per call.
- Uses a wrapping count query: `select count(*) from ()`.

Safety notes
------------

[](#safety-notes)

- Use named bindings (`:status`) instead of interpolating values to avoid SQL injection.
- Ensure `base_query` is valid on the chosen connection.
- Disable or restrict who can edit report definitions in production.

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

[](#contributing)

- Fork or add as a local path repo, adjust code, and run `composer dump-autoload`.
- PRs and issues are welcome.

License
-------

[](#license)

MIT

###  Health Score

31

—

LowBetter than 65% of packages

Maintenance61

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

Total

4

Last Release

245d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5915383ac10e7c148c23e142195199c8e7909acc2cda2003c26e688090956014?d=identicon)[EngMEita](/maintainers/EngMEita)

---

Top Contributors

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

---

Tags

laravelpdfexportgeneratorexcelworddatatablesreportingreports

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/meita-reports-generator/health.svg)

```
[![Health](https://phpackages.com/badges/meita-reports-generator/health.svg)](https://phpackages.com/packages/meita-reports-generator)
```

###  Alternatives

[unopim/unopim

UnoPim Laravel PIM

10.8k2.5k](/packages/unopim-unopim)[bagisto/bagisto

Bagisto Laravel E-Commerce

28.0k175.2k9](/packages/bagisto-bagisto)[typicms/base

A modular multilingual CMS built with Laravel, enabling developers to manage structured content like pages, news, events, and more.

1.6k20.4k](/packages/typicms-base)[dcat-plus/laravel-admin

dcat-plus admin

1494.6k10](/packages/dcat-plus-laravel-admin)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

762297.9k53](/packages/civicrm-civicrm-core)[helsingborg-stad/municipio

A bootstrap theme for creating municipality sites.

4028.6k10](/packages/helsingborg-stad-municipio)

PHPackages © 2026

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