PHP code example of eslam-dev / laravel-searchable
1. Go to this page and download the library: Download eslam-dev/laravel-searchable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
eslam-dev / laravel-searchable example snippets
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();
});
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'],
];
}
// 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();
// Force LIKE search
$products = Product::searchLike('title_search', 'partial')->get();
// Search multiple columns with LIKE
$products = Product::searchLike(['title_search', 'description_search'], 'text')->get();
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();
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();