Download the PHP package mayaram/laravel-ocr without Composer
On this page you can find all versions of the php package mayaram/laravel-ocr. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mayaram/laravel-ocr
More information about mayaram/laravel-ocr
Files in mayaram/laravel-ocr
Package laravel-ocr
Short Description Laravel OCR & Document Data Extractor - A powerful OCR and document parsing engine for Laravel
License MIT
Informations about the package laravel-ocr
Laravel OCR & Document Intelligence
Turn any image or PDF into structured, actionable data.
A powerful, developer-friendly Laravel package that reads text from images and PDFs, understands the content, fixes scanning errors with AI, and delivers clean, structured data directly to your application.
Why this package? Most OCR tools just give you a dump of raw text. This package gives you typed DTOs, structured fields, and confidence scores. It knows the difference between an Invoice Number and a Phone Number.
๐ธ Demo
๐ Table of Contents
- โจ Features
- ๐ Architecture
- ๐ Installation
- Compatibility Matrix
- Quick Start
- Install via Composer
- Publish Configuration & Assets
- Publish Views (Optional)
- Install Tesseract (Default Driver)
- โ๏ธ Configuration
- OCR Driver Selection
- Tesseract
- Google Cloud Vision
- AWS Textract
- Azure Computer Vision
- AI Cleanup (via Laravel AI SDK)
- Queue Configuration
- Troubleshooting Setup
- Storage & Security
- ๐ Usage
- Simple Text Extraction
- Smart Parsing (Structured Data via OcrResult DTO)
- Batch Processing
- Working with Line Items & Tables
- Templates
- Workflows
- Switching Drivers at Runtime
- Document Metadata Extraction
- Working with Processed Documents
- ๐ฅ๏ธ Artisan Commands
- Create a Template
- Process a Document
- ๐จ Blade Component
- ๐๏ธ Database Schema
- ๐งฉ OCR Driver Interface
- Supported Formats by Driver
- Building a Custom Driver
- ๐ค AI Cleanup Details
- Basic Rules (No API Required)
- AI-Powered Cleanup (via Laravel AI SDK)
- ๐งช Testing
- ๐ API Reference
- LaravelOcr Facade
- DocumentParser
- OcrResult DTO
- TemplateManager
- ๐ License
โจ Features
- ๐ง Multi-Driver OCR Engine: Seamlessly switch between Tesseract (offline/privacy-first), Google Cloud Vision, AWS Textract, or Azure Computer Vision drivers.
- ๐ค Optional AI Cleanup: Can use the
laravel/aiSDK with theCleanupAgentto fix OCR typos (e.g.,arnountโamount,nurnberโnumber) and normalize data formats. Supports OpenAI, Anthropic, Gemini, Ollama, DeepSeek, Groq, Mistral, and more when the AI stack is installed. - ๐ฆ Typed DTOs: Returns an
OcrResultdata transfer object withtext,confidence,bounds, andmetadataproperties โ not just raw arrays. - ๐ Advanced Invoice Extraction: Specialized algorithms to extract line items (quantity, description, unit price, total), subtotals, tax, shipping, and totals from complex invoice layouts.
- ๐ Auto-Classification: Automatically detects document types (Invoice, Receipt, Contract, Purchase Order, Shipping, General) using keyword scoring.
- ๐ Reusable Templates: Define document templates with regex patterns and positional extraction to target specific fields. Supports template creation, import/export, and auto-matching.
- โก Workflows: Define custom processing pipelines per document type in your config (e.g., "If Invoice โ Extract Tables โ Verify Required Fields").
- ๐จ Blade Component: Built-in
<x-laravel-ocr::document-preview>component to visualize results with bounding box overlays, inline editing, and data export. - ๐ฅ๏ธ Artisan Commands: CLI tools for environment diagnostics (
laravel-ocr:doctor), template creation (laravel-ocr:create-template), and document processing (laravel-ocr:process). - ๐พ Database Persistence: Optionally save processed results to the
ocr_processed_documentstable with template associations, confidence scores, and processing times. - ๐ Enterprise Security: Encrypted storage options, MIME-type validation, malware scanning, and full offline support for sensitive data.
๐ Architecture
๐ Installation
Requires PHP 8.2+.
Core OCR features support Laravel 9 / 10 / 11 / 12 / 13.
AI cleanup is optional and depends on the laravel/ai package version you install.
Compatibility Matrix
| Capability | PHP | Laravel | Extra Package |
|---|---|---|---|
| Core OCR, templates, parsing, console commands | 8.2+ |
9+ |
None |
AI cleanup with provider=basic |
8.2+ |
9+ |
None |
AI cleanup with laravel/ai |
Depends on the laravel/ai version you install |
Depends on the laravel/ai version you install |
laravel/ai |
If you need the widest compatibility, keep AI cleanup on provider=basic.
Quick Start
Install the package, publish the config and migrations, verify the runtime, then process a document:
For AI cleanup, install laravel/ai separately and configure your provider credentials before using --ai-cleanup.
1. Install via Composer
Optional: Install AI Cleanup Support
laravel/ai has its own PHP/Laravel constraints. Check the version you install if you need AI cleanup on top of the core OCR package.
2. Publish Configuration & Assets
3. Publish Views (Optional)
4. Install Tesseract (Default Driver)
โ๏ธ Configuration
Set your preferred driver and credentials in your .env file.
OCR Driver Selection
Tesseract (Offline / Privacy-First โ Default)
All processing happens on your server. No data leaves your infrastructure.
Google Cloud Vision
Requires:
composer require google/cloud-vision
AWS Textract
Included:
aws/aws-sdk-phpis a core dependency.
Azure Computer Vision
AI Cleanup (via Laravel AI SDK)
Enable AI-powered OCR post-processing to fix scanning errors and normalize data formats. This feature is optional and requires laravel/ai to be installed in the host app. The package uses a dedicated CleanupAgent that supports multiple LLM providers.
Supported AI Providers
Set the API key for your chosen provider:
| Provider | Env Variable | Driver Key |
|---|---|---|
| OpenAI | OPENAI_API_KEY |
openai |
| Anthropic | ANTHROPIC_API_KEY |
anthropic |
| Google Gemini | GEMINI_API_KEY |
gemini |
| Ollama (Local) | OLLAMA_API_KEY |
ollama |
| DeepSeek | DEEPSEEK_API_KEY |
deepseek |
| Groq | GROQ_API_KEY |
groq |
| Mistral | MISTRAL_API_KEY |
mistral |
| Azure OpenAI | AZURE_OPENAI_API_KEY |
azure |
| Cohere | COHERE_API_KEY |
cohere |
| OpenRouter | OPENROUTER_API_KEY |
openrouter |
| xAI | XAI_API_KEY |
xai |
| Jina | JINA_API_KEY |
jina |
| VoyageAI | VOYAGEAI_API_KEY |
voyageai |
| ElevenLabs | ELEVENLABS_API_KEY |
eleven |
Queue Configuration
Process documents asynchronously:
๐ฉบ Doctor Command
Use the doctor command to verify the package runtime setup before processing documents:
It checks:
- PHP version compatibility
- The configured default OCR driver
- Tesseract binary availability when Tesseract is the active driver
- Optional AI cleanup readiness
Troubleshooting Setup
Use these checks before debugging extraction quality:
Common setup issues:
Tesseract binary not found: setTESSERACT_BINARYto the real binary path on your machine.- AI cleanup warning: install
laravel/ai, then configureLARAVEL_OCR_AI_PROVIDERand the matching API key. - PDF conversion issues: ensure the host has the extensions and system tools required by your PDF/image pipeline.
- Laravel install conflicts: check the PHP/Laravel constraints of
laravel/aiseparately from the core package.
Storage & Security
๐ Usage
1. Simple Text Extraction
The LaravelOcr facade provides a simple entry point via the OCRManager.
If you only need OCR text and not structured parsing, this is the simplest integration point.
2. Smart Parsing (Structured Data via OcrResult DTO)
For powerful data extraction, use the DocumentParser. It returns a typed OcrResult DTO with text, confidence, bounds, and metadata properties.
Use DocumentParser when you want document classification, template support, field extraction, metadata, or optional cleanup in one pipeline.
3. Batch Processing
Process multiple documents at once:
4. Working with Line Items & Tables
The package includes an Advanced Invoice Extractor capable of parsing complex invoice tables into structured arrays.
5. Templates
Define reusable templates to target specific fields using regex patterns. Templates are stored in the database and support import/export.
6. Workflows
Configure processing pipelines in config/laravel-ocr.php to standardize how different document types are handled.
7. Switching Drivers at Runtime
8. Document Metadata Extraction
9. Working with Processed Documents
๐ฅ๏ธ Artisan Commands
Create a Template
Process a Document
Flags:
| Flag | Description |
|---|---|
--template=ID |
Use a specific template |
--type=TYPE |
Set document type (invoice, receipt, etc.) |
--ai-cleanup |
Enable AI-powered cleanup |
--save |
Save results to database |
--output=FORMAT |
Output format: json or table (default) |
Check Environment Health
Run this first on a new machine, server, or CI environment.
๐จ Blade Component
Preview extracted documents and data directly in your UI with the built-in Alpine.js component.
Props:
| Prop | Type | Default | Description |
|---|---|---|---|
document |
array |
required | Document data with url, documentId, and fields |
show-overlay |
bool |
false |
Show bounding box overlays on the document |
show-actions |
bool |
true |
Show Save/Export/Reprocess action buttons |
show-image |
bool |
true |
Use <img> tag (true) or <iframe> (false) |
Expected Document Structure:
Features:
- Click fields to highlight them on the document
- Inline editing of extracted values
- Confidence badges: ๐ข High (โฅ80%), ๐ก Medium (โฅ60%), ๐ด Low (<60%)
- Export extracted data as JSON
- Reprocess documents with one click
๐๏ธ Database Schema
The package creates three tables:
ocr_templates
| Column | Type | Description |
|---|---|---|
id |
bigint | Primary key |
name |
string | Template name |
description |
text | Optional description |
type |
string(50) | Document type (invoice, receipt, etc.) |
layout |
json | Layout configuration |
is_active |
boolean | Whether template is active |
version |
string(10) | Template version (default: 1.0) |
ocr_template_fields
| Column | Type | Description |
|---|---|---|
id |
bigint | Primary key |
template_id |
foreignId | References ocr_templates |
key |
string(50) | Field identifier (snake_case) |
label |
string | Human-readable label |
type |
string(30) | Field type: string, numeric, date, currency, email, phone |
pattern |
text | Regex pattern for extraction |
position |
json | Positional extraction config (line, start, end) |
validators |
json | Validation rules (required, regex, length, type) |
default_value |
string | Fallback value |
order |
integer | Display order |
ocr_processed_documents
| Column | Type | Description |
|---|---|---|
id |
bigint | Primary key |
original_filename |
string | Original file name |
document_type |
string(50) | Detected or specified type |
extracted_data |
json | Full extraction result |
template_id |
foreignId | Template used (nullable) |
confidence_score |
decimal(3,2) | Overall confidence |
processing_time |
decimal(8,3) | Time in seconds |
user_id |
bigint | User who processed (nullable) |
status |
string(20) | completed, failed, etc. |
error_message |
text | Error details if failed |
๐งฉ OCR Driver Interface
All drivers implement the Mayaram\LaravelOcr\Contracts\OCRDriver interface:
Supported Formats by Driver
| Format | Tesseract | Google Vision | AWS Textract | Azure |
|---|---|---|---|---|
| JPG/JPEG | โ | โ | โ | โ |
| PNG | โ | โ | โ | โ |
| โ | โ | โ | โ | |
| TIFF | โ | โ | โ | โ |
| BMP | โ | โ | โ | โ |
| GIF | โ | โ | โ | โ |
| WebP | โ | โ | โ | โ |
Building a Custom Driver
๐ค AI Cleanup Details
The AICleanupService provides two modes:
Basic Rules (No API Required)
Set provider to basic to use built-in typo correction and field normalization without any AI provider:
Built-in corrections:
- Common OCR typos:
invOiceโinvoice,arnountโamount,nurnberโnumber,custornerโcustomer,payrnentโpayment - OCR pattern fixes:
rnโm,Obefore numbers โ0,lbefore numbers โ1 - Field normalization by type: numeric, date (โ
Y-m-d), currency, email, phone
AI-Powered Cleanup (via Laravel AI SDK)
Uses the CleanupAgent with your configured LLM provider for intelligent correction:
The agent is instructed to:
- Fix typos and OCR errors contextually
- Standardize formats (dates to
YYYY-MM-DD, currency to decimal) - Preserve values it can't confidently fix
- Return valid JSON matching the input structure
Custom Prompt
You can pass additional instructions to the AI cleanup agent to customize its behavior:
Or set a default custom prompt in config/laravel-ocr.php:
The custom prompt is appended as "Additional Instructions" to the default cleanup prompt, so the base OCR correction behavior is always preserved.
๐งช Testing
The package uses Pest for testing with three test suites:
Tests use SQLite in-memory database automatically via phpunit.xml configuration.
Current coverage includes:
- parsing and template application
- console commands
- AI cleanup flow with mocked AI responses
- end-to-end package flow through integration tests
๐ API Reference
LaravelOcr Facade (via OCRManager)
| Method | Returns | Description |
|---|---|---|
extract($document, $options) |
array |
Extract text from document |
extractWithTemplate($document, $templateId, $options) |
array |
Extract and apply template |
extractTable($document, $options) |
array |
Extract table data |
extractBarcode($document, $options) |
array |
Extract barcode |
extractQRCode($document, $options) |
array |
Extract QR code |
driver($name) |
OCRDriver |
Switch to a specific driver |
DocumentParser (via app('laravel-ocr.parser'))
| Method | Returns | Description |
|---|---|---|
parse($document, $options) |
OcrResult |
Full parsing pipeline |
parseBatch($documents, $options) |
OcrResult[] |
Process multiple documents |
parseWithWorkflow($document, $workflow) |
OcrResult |
Parse using a named workflow |
extractMetadata($document) |
array |
Extract file & PDF metadata |
OcrResult DTO
| Property | Type | Description |
|---|---|---|
text |
string |
Full extracted text |
confidence |
float |
Overall confidence score (0โ1) |
bounds |
array |
Bounding box / layout data |
metadata |
array |
Processing time, document type, fields, template used, etc. |
TemplateManager (via app('laravel-ocr.templates'))
| Method | Returns | Description |
|---|---|---|
create($data) |
DocumentTemplate |
Create a template with fields |
applyTemplate($extractedData, $templateId) |
array |
Apply template to extracted data |
findTemplateByContent($text) |
?DocumentTemplate |
Auto-detect matching template |
importTemplate($filePath) |
DocumentTemplate |
Import from JSON file |
exportTemplate($templateId) |
string |
Export as JSON string |
๐ License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-ocr with dependencies
illuminate/support Version ^9.0|^10.0|^11.0|^12.0|^13.0
thiagoalessio/tesseract_ocr Version ^2.12
smalot/pdfparser Version ^2.0
intervention/image Version ^3.0
guzzlehttp/guzzle Version ^7.0
aws/aws-sdk-php Version ^3.369
ext-json Version *