PHPackages                             eslam-dev/laravel-searchable - 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. [Database &amp; ORM](/categories/database)
4. /
5. eslam-dev/laravel-searchable

ActiveLibrary[Database &amp; ORM](/categories/database)

eslam-dev/laravel-searchable
============================

Laravel Searchable — dedicated searchable columns for Eloquent with cleaning, FULLTEXT search, and rebuild tooling

1.0.1(4w ago)04↓100%MITPHPPHP ^8.2

Since May 2Pushed 4w agoCompare

[ Source](https://github.com/eslam-dev/laravel-searchable)[ Packagist](https://packagist.org/packages/eslam-dev/laravel-searchable)[ RSS](/packages/eslam-dev-laravel-searchable/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (7)Versions (3)Used By (0)

Laravel Searchable
==================

[](#laravel-searchable)

A Laravel package for dedicated searchable text columns on Eloquent models: automatic fill on save, text cleaning, and MySQL FULLTEXT search.

[![Latest Version](https://camo.githubusercontent.com/34e695c6016bc2a934a96bed696e29b2f2ab562a7134d65a55d00653cd506bea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75652e737667)](https://github.com/eslam-dev/laravel-searchable)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

Features
--------

[](#features)

✅ **Migration Macros** - Simple `searchableColumn()` macro for creating LONGTEXT columns with FULLTEXT indexes
✅ **Automatic Population** - Searchable columns are automatically updated on model save
✅ **Text Cleaning** - Comprehensive text normalization (HTML stripping, Arabic normalization, diacritic removal)
✅ **FULLTEXT Search** - Native MySQL FULLTEXT search with natural language mode
✅ **Multiple Columns** - Support for multiple searchable columns per model
✅ **Relationship Support** - Extract text from relationships using dot notation
✅ **Translatable Fields** - Automatic extraction from JSON/translatable fields
✅ **Queue Support** - Rebuild searchable columns via queue for large datasets
✅ **Highly Configurable** - Customize cleaning rules, separators, and extraction methods

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

[](#requirements)

- PHP 8.2+
- Laravel 12.0+
- MySQL 5.6+ or MariaDB 10.0+

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

[](#installation)

Install via Composer:

```
composer require eslam-dev/laravel-searchable
```

Publish the configuration file:

```
php artisan vendor:publish --tag=laravel-searchable-config
```

Quick Start
-----------

[](#quick-start)

### 1. Add Searchable Columns to Migration

[](#1-add-searchable-columns-to-migration)

```
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->json('title');
    $table->json('description');
    $table->string('sku');

    // Add searchable columns with automatic FULLTEXT index
    $table->searchableColumn('title_search');
    $table->searchableColumn('description_search');
    $table->searchableColumn('combined_search');

    $table->timestamps();
});
```

### 2. Add Trait to Model

[](#2-add-trait-to-model)

```
use Illuminate\Database\Eloquent\Model;
use EslamDev\SearchableColumns\Traits\HasSearchableColumns;

class Product extends Model
{
    use HasSearchableColumns;

    protected array $searchableColumns = [
        // Simple: one source field
        'title_search' => ['title'],

        // Multiple source fields
        'description_search' => ['description', 'short_description'],

        // Combined search across multiple fields
        'combined_search' => ['title', 'description', 'sku'],
    ];
}
```

### 3. Search Your Data

[](#3-search-your-data)

```
// Search across all defined searchable columns
$products = Product::search('iphone 13 pro')->get();

// Search specific column
$products = Product::searchIn('title_search', 'iphone')->get();

// Search multiple columns
$products = Product::searchIn(['title_search', 'description_search'], 'phone')->get();

// Combine with other filters
$products = Product::search('laptop')
    ->where('status', 'published')
    ->inStock()
    ->get();
```

Advanced Usage
--------------

[](#advanced-usage)

### Relationship Fields

[](#relationship-fields)

Extract text from related models:

```
protected array $searchableColumns = [
    'search_text' => [
        'title',
        'description',
        'brand.name',           // BelongsTo relationship
        'categories.*.name',    // BelongsToMany/HasMany
    ],
];
```

### Translatable Fields

[](#translatable-fields)

For models using Spatie's Translatable or JSON fields:

```
protected array $searchableColumns = [
    'search_text' => [
        'sources' => ['title', 'description', 'brand.name'],
        'extract_translations' => 'all',  // 'all', 'default', or false
        'separator' => ' | ',
    ],
];
```

**Options:**

- `'all'` - Combines all translations: "Phone هاتف"
- `'default'` - Uses only the default locale
- `false` - Treats as regular string

### Custom Cleaning Rules

[](#custom-cleaning-rules)

Override cleaning rules per model:

```
protected array $searchableCleaningRules = [
    'strip_html' => true,
    'decode_entities' => true,
    'normalize_arabic' => true,
    'remove_diacritics' => true,
    'lowercase' => true,
    'remove_symbols' => false,  // Keep symbols
    'collapse_whitespace' => true,
];
```

### LIKE Fallback

[](#like-fallback)

For cases where FULLTEXT isn't suitable:

```
// Force LIKE search
$products = Product::searchLike('title_search', 'partial')->get();

// Search multiple columns with LIKE
$products = Product::searchLike(['title_search', 'description_search'], 'text')->get();
```

Artisan Commands
----------------

[](#artisan-commands)

### Rebuild Searchable Columns

[](#rebuild-searchable-columns)

Rebuild searchable columns for existing records:

```
# Rebuild all models
php artisan searchable:rebuild

# Specific model
php artisan searchable:rebuild --model="App\Models\Product"

# With progress bar
php artisan searchable:rebuild --model="App\Models\Product" --verbose

# Queue processing for large datasets
php artisan searchable:rebuild --model="App\Models\Product" --queue

# Specific queue
php artisan searchable:rebuild --model="App\Models\Product" --queue --queue-name=search-rebuild
```

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

[](#configuration)

The configuration file `config/laravel-searchable.php` provides extensive customization options:

```
return [
    // Enable/disable FULLTEXT indexes
    'enable_fulltext' => true,

    // Default text cleaning rules
    'cleaning_rules' => [
        'strip_html' => true,
        'decode_entities' => true,
        'normalize_arabic' => true,
        'remove_diacritics' => true,
        'lowercase' => true,
        'remove_symbols' => true,
        'collapse_whitespace' => true,
    ],

    // Arabic normalization mappings
    'arabic_normalizations' => [
        'أ' => 'ا',
        'إ' => 'ا',
        'آ' => 'ا',
        'ة' => 'ه',
        'ى' => 'ي',
    ],

    // Translation extraction mode
    'extract_translations' => 'all',  // 'all', 'default', or false

    // Queue settings
    'queue' => 'default',
    'chunk_size' => 500,

    // ... and more
];
```

Text Cleaning Pipeline
----------------------

[](#text-cleaning-pipeline)

The package applies a comprehensive cleaning pipeline:

1. **Strip HTML** - Removes all HTML tags
2. **Decode Entities** - Converts HTML entities (`&amp;` → `&`)
3. **Normalize Arabic** - Standardizes Arabic character variants
4. **Remove Diacritics** - Strips Arabic tashkeel marks
5. **Convert to Lowercase** - Standardizes case for better matching
6. **Remove Symbols** - Strips punctuation and special characters
7. **Collapse Whitespace** - Normalizes spacing

Performance Optimization
------------------------

[](#performance-optimization)

### MySQL Configuration

[](#mysql-configuration)

For better Arabic search, configure MySQL:

```
# /etc/mysql/my.cnf
[mysqld]
ft_min_word_length = 3
```

Then rebuild the FULLTEXT index:

```
OPTIMIZE TABLE products;
```

### Queue Processing

[](#queue-processing)

For large datasets, use queue processing:

```
php artisan searchable:rebuild --model="App\Models\Product" --queue
```

Configure chunk size in `config/laravel-searchable.php`:

```
'chunk_size' => 500,  // Adjust based on your needs
```

### Eager Loading

[](#eager-loading)

The package automatically eager loads relationships used in searchable columns to prevent N+1 queries.

Testing
-------

[](#testing)

The package includes comprehensive unit and feature tests:

```
composer test
```

### Test Requirements

[](#test-requirements)

Tests require a MySQL database. Configure in `phpunit.xml`:

```

```

Examples
--------

[](#examples)

### E-commerce Product Search

[](#e-commerce-product-search)

```
class Product extends Model
{
    use HasSearchableColumns, HasTranslations;

    public $translatable = ['title', 'description'];

    protected array $searchableColumns = [
        'search_text' => [
            'title',
            'description',
            'sku',
            'barcode',
            'brand.name',
            'categories.*.name',
        ],
    ];
}

// Search usage
$results = Product::search('iphone 13 pro')
    ->published()
    ->inStock()
    ->get();
```

### Multi-language Content

[](#multi-language-content)

```
class Article extends Model
{
    use HasSearchableColumns, HasTranslations;

    public $translatable = ['title', 'content'];

    protected array $searchableColumns = [
        'search_text' => [
            'sources' => ['title', 'content', 'author.name'],
            'extract_translations' => 'all',  // Index all languages
        ],
    ];
}

// Searches in both English and Arabic
$results = Article::search('tutorial')->get();
```

### Selective Searchable Columns

[](#selective-searchable-columns)

```
class Post extends Model
{
    use HasSearchableColumns;

    protected array $searchableColumns = [
        'title_search' => ['title'],
        'content_search' => ['content', 'excerpt'],
        'full_search' => ['title', 'content', 'excerpt', 'tags.*.name'],
    ];
}

// Search only titles
Post::searchIn('title_search', 'laravel')->get();

// Search content
Post::searchIn('content_search', 'tutorial')->get();

// Full search
Post::search('laravel tutorial')->get();
```

Troubleshooting
---------------

[](#troubleshooting)

### FULLTEXT Search Not Working

[](#fulltext-search-not-working)

1. Ensure you're using MySQL 5.6+ or MariaDB 10.0+
2. Check that FULLTEXT indexes are created: ```
    SHOW INDEX FROM products WHERE Key_name LIKE '%search%';
    ```
3. Verify minimum word length matches your content: ```
    SHOW VARIABLES LIKE 'ft_min_word_length';
    ```

### Arabic Search Issues

[](#arabic-search-issues)

1. Set `ft_min_word_length = 3` in MySQL configuration
2. Rebuild FULLTEXT indexes: `OPTIMIZE TABLE products;`
3. Verify Arabic normalization is enabled in config

### Performance Issues

[](#performance-issues)

1. Use queue processing for bulk rebuilds
2. Adjust chunk size in configuration
3. Add database indexes on frequently filtered columns
4. Consider using Laravel Scout for more advanced search needs

Security
--------

[](#security)

If you discover any security-related issues, please open a private security advisory on the repository instead of using the public issue tracker.

License
-------

[](#license)

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

Credits
-------

[](#credits)

- **eslam-dev**
- [All Contributors](../../contributors)

Support
-------

[](#support)

- 🐛 Issues: [GitHub Issues](https://github.com/eslam-dev/laravel-searchable/issues)
- 📖 Documentation: [Full Documentation](https://github.com/eslam-dev/laravel-searchable/wiki)

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance94

Actively maintained with recent releases

Popularity5

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

Total

2

Last Release

29d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/21009117?v=4)[eslam el sherif](/maintainers/eslam-dev)[@eslam-dev](https://github.com/eslam-dev)

---

Top Contributors

[![eslam-dev](https://avatars.githubusercontent.com/u/21009117?v=4)](https://github.com/eslam-dev "eslam-dev (2 commits)")

---

Tags

searchlaravelmysqleloquentsearchablefulltextlaravel-searchable

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/eslam-dev-laravel-searchable/health.svg)

```
[![Health](https://phpackages.com/badges/eslam-dev-laravel-searchable/health.svg)](https://phpackages.com/packages/eslam-dev-laravel-searchable)
```

###  Alternatives

[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.4k](/packages/larastan-larastan)[laravel/ai

The official AI SDK for Laravel.

9782.1M153](/packages/laravel-ai)[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.6k29.9M42](/packages/kirschbaum-development-eloquent-power-joins)[spatie/laravel-health

Monitor the health of a Laravel application

88011.3M149](/packages/spatie-laravel-health)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

436834.4k1](/packages/clickbar-laravel-magellan)

PHPackages © 2026

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