PHP code example of shammaa / laravel-search

1. Go to this page and download the library: Download shammaa/laravel-search 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/ */

    

shammaa / laravel-search example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Shammaa\LaravelSearch\Traits\Searchable;

class Article extends Model
{
    use Searchable;

    /**
     * Define searchable fields with priority weights.
     * Higher priority = more important in search results.
     */
    protected $searchable = [
        'title' => ['priority' => 2.0],      // 2x more important
        'content' => ['priority' => 1.0],     // Base importance
        'description' => ['priority' => 1.5], // 1.5x more important
    ];

    /**
     * Define filterable fields for WHERE clauses.
     */
    protected $filterable = [
        'status',
        'category_id',
        'author_id',
        'published_at',
        'tags',
    ];

    /**
     * Define sortable fields.
     */
    protected $sortable = [
        'published_at',
        'views',
        'created_at',
    ];
}

// Simple search
$results = Article::search('Laravel')->get();

// Advanced search with filters
$results = Article::search('Laravel')
    ->where('status', 'published')
    ->where('category_id', 5)
    ->whereBetween('published_at', [$start, $end])
    ->orderBy('relevance', 'desc')
    ->paginate(20);

// Autocomplete
$suggestions = Article::autocomplete('Lara');

// Simple search
$articles = Article::search('Laravel')->get();

// Search with pagination
$articles = Article::search('Laravel')->paginate(20);

// Limit and offset
$articles = Article::search('Laravel')
    ->limit(50)
    ->offset(100)
    ->get();

// Count results
$count = Article::search('Laravel')->count();

// Simple where
Article::search('Laravel')
    ->where('status', 'published')
    ->where('category_id', 5)
    ->where('is_featured', true)
    ->get();

// Where with operator
Article::search('Laravel')
    ->where('views', '>', 1000)
    ->get();

// WhereIn
Article::search('Laravel')
    ->whereIn('tags', ['php', 'laravel', 'symfony'])
    ->get();

// WhereNotIn
Article::search('Laravel')
    ->whereNotIn('author_id', [1, 2, 3])
    ->get();

// WhereNull
Article::search('Laravel')
    ->whereNull('deleted_at')
    ->get();

// WhereNotNull
Article::search('Laravel')
    ->whereNotNull('published_at')
    ->get();

// WhereBetween
Article::search('Laravel')
    ->whereBetween('published_at', ['2024-01-01', '2024-12-31'])
    ->get();

// WhereBetween with dates
Article::search('Laravel')
    ->whereBetween('created_at', [
        now()->subDays(30),
        now()
    ])
    ->get();

$results = Article::search('Laravel')
    ->facets(['category', 'author', 'tags', 'year'])
    ->get();

// Access facets
$facets = $results->facets;
// [
//     'category' => [
//         ['value' => 'Tutorial', 'count' => 45],
//         ['value' => 'News', 'count' => 23],
//     ],
//     'author' => [...],
//     ...
// ]

// Facets work with pagination too
$paginated = Article::search('Laravel')
    ->facets(['category', 'author'])
    ->paginate(20);
    
$facets = $paginated->facets;

// Sort by relevance (default)
Article::search('Laravel')
    ->orderBy('relevance', 'desc')
    ->get();

// Sort by field
Article::search('Laravel')
    ->orderBy('published_at', 'desc')
    ->get();

// Multiple sorts
Article::search('Laravel')
    ->orderBy('relevance', 'desc')
    ->orderBy('published_at', 'desc')
    ->orderBy('views', 'desc')
    ->get();

// Get autocomplete suggestions
$suggestions = Article::autocomplete('Lara');
// Returns: ['Laravel', 'Laravel Nova', 'Laravel Horizon']

// With custom limit
$suggestions = Article::autocomplete('Lara', 20);

// Using the facade
use Shammaa\LaravelSearch\Facades\Search;

$suggestions = Search::autocomplete(Article::class, 'Lara', 10);

// Search in Arabic
$articles = Article::search('برمجة')->get();

// Mixed Arabic and English
$articles = Article::search('Laravel برمجة')->get();

use Shammaa\LaravelSearch\Facades\Search;

// Search
$results = Search::search(Article::class, 'Laravel')
    ->where('status', 'published')
    ->get();

// Autocomplete
$suggestions = Search::autocomplete(Article::class, 'Lara');

// Popular searches
$popular = Search::popularSearches(10);

// Search statistics
$stats = Search::stats();

// Clear cache
Search::clearCache();

'mysql' => [
    // Search mode: NATURAL_LANGUAGE or BOOLEAN
    'search_mode' => env('MYSQL_SEARCH_MODE', 'NATURAL_LANGUAGE'),
    
    // Minimum word length for FULLTEXT search
    'min_word_length' => env('MYSQL_MIN_WORD_LENGTH', 4),
    
    // Index name prefix
    'index_prefix' => env('MYSQL_INDEX_PREFIX', 'ft_'),
],

'indexing' => [
    // Auto-create indexes when models are created
    'auto' => env('SEARCH_AUTO_INDEX', true),
    
    // Use queue for indexing operations
    'queue' => env('SEARCH_QUEUE_INDEX', true),
    
    // Queue name for indexing jobs
    'queue_name' => env('SEARCH_QUEUE_NAME', 'search'),
    
    // Batch size for bulk operations
    'batch_size' => env('SEARCH_BATCH_SIZE', 1000),
    
    // Chunk size for processing
    'chunk_size' => env('SEARCH_CHUNK_SIZE', 100),
],

'cache' => [
    // Enable search result caching
    'enabled' => env('SEARCH_CACHE_ENABLED', true),
    
    // Cache store to use
    'store' => env('SEARCH_CACHE_STORE', 'default'),
    
    // Cache TTL in seconds (1 hour)
    'ttl' => env('SEARCH_CACHE_TTL', 3600),
    
    // Popular searches cache TTL (2 hours)
    'popular_ttl' => env('SEARCH_CACHE_POPULAR_TTL', 7200),
    
    // Autocomplete cache TTL (30 minutes)
    'autocomplete_ttl' => env('SEARCH_CACHE_AUTOCOMPLETE_TTL', 1800),
],

'analytics' => [
    // Enable search analytics
    'enabled' => env('SEARCH_ANALYTICS_ENABLED', true),
    
    // Analytics table name
    'table' => env('SEARCH_ANALYTICS_TABLE', 'search_analytics'),
    
    // Track searches with no results
    'track_empty' => env('SEARCH_ANALYTICS_TRACK_EMPTY', false),
],

'performance' => [
    // Eager load relationships
    'eager_load' => env('SEARCH_EAGER_LOAD', true),
    
    // Select only needed fields
    'select_fields' => env('SEARCH_SELECT_FIELDS', false),
    
    // Maximum results per query
    'max_results' => env('SEARCH_MAX_RESULTS', 10000),
],

// In config/search.php
'mysql' => [
    'search_mode' => 'NATURAL_LANGUAGE',
],

// In config/search.php
'mysql' => [
    'search_mode' => 'BOOLEAN',
],

// Must contain "Laravel"
Article::search('+Laravel')->get();

// Must contain "Laravel" but not "Vue"
Article::search('+Laravel -Vue')->get();

// Exact phrase
Article::search('"Laravel Framework"')->get();

// Wildcard
Article::search('Lara*')->get();

// In config/search.php
'indexing' => [
    'queue' => true,
    'queue_name' => 'search',
],

use App\Models\Article;

// Manually create index for a model instance
$article = Article::find(1);
$article->searchable();

// This is automatically called on model creation if auto-indexing is enabled

   // Make sure fields are defined
   protected $searchable = [
       'title' => ['priority' => 1.0],
       'content' => ['priority' => 1.0],
   ];
   

   Article::search('query')->limit(100)->get();
   
bash
php artisan vendor:publish --tag=search-config
bash
php artisan search:index "App\Models\Article"
bash
# Create FULLTEXT index for a model
php artisan search:index "App\Models\Article"

# Use queue for indexing (recommended for large datasets)
php artisan search:index "App\Models\Article" --queue

# Reindex (drops and recreates FULLTEXT index)
php artisan search:reindex "App\Models\Article"

# Clear index
php artisan search:clear "App\Models\Article"
bash
php artisan queue:work --queue=search
bash
php artisan search:reindex "App\Models\Article"
bash
   php artisan search:stats --model="App\Models\Article"