PHP code example of openplain / laravel-lightsearch

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

    

openplain / laravel-lightsearch example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    protected $fillable = ['title', 'excerpt', 'content'];

    public function toSearchableArray(): array
    {
        return [
            'title' => $this->title,
            'excerpt' => $this->excerpt,
            'content' => $this->content,
        ];
    }
}

// Basic search
$posts = Post::search('laravel')->get();

// Paginated results
$posts = Post::search('laravel')->paginate(15);

// With query constraints
$posts = Post::search('laravel')
    ->where('published', true)
    ->orderBy('created_at', 'desc')
    ->get();

// Fuzzy search (PostgreSQL only)
$posts = Post::search('laravle')->fuzzy(0.3)->get();

'model_field_weights' => [
    \App\Models\Post::class => [
        'title' => 3,    // Title matches ranked 3x higher
        'excerpt' => 2,  // Excerpt matches ranked 2x higher
        'content' => 1,  // Content has default weight
    ],
],

'stopwords' => [
    'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',
    'has', 'he', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the',
    'to', 'was', 'will', 'with', // ... add your own
],

'min_token_length' => 2,  // Default: 2 characters

'connection' => env('LIGHTSEARCH_DB_CONNECTION', null),

// Automatically finds "Laravel" even with typo
Post::search('laravle')->get();

// Automatically finds "Tórshavn" without accents
Address::search('Torshavn')->get();

Post::search('laravle')->fuzzy(0.5)->get();  // Stricter (default: 0.3)
Post::search('laravle')->fuzzy(0.2)->get();  // Looser
bash
php artisan vendor:publish --tag=lightsearch-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=lightsearch-config