PHP code example of whitecube / laravel-search-builder

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

    

whitecube / laravel-search-builder example snippets


use \App\Models\Product;
use \Whitecube\SearchBuilder\SearchBuilder;

$builder = new SearchBuilder(Product::class); // You can also pass it an instance of your model

use Whitecube\SearchBuilder\HasSearchBuilder;

class Product extends Model
{
    use HasSearchBuilder;
}

$builder = Product::searchBuilder();

Product::searchBuilder()
    ->search(Product::select('id')->where('ref', 'SEARCH_STRING'), score: 100)
    ->search(Product::select('id')->where('name', 'SEARCH_STRING'), score: 50);

Product::searchBuilder()
    ->search(Product::select('id')->where('ref', 'SEARCH_STRING'), score: 100) // score = 100
    ->search(Product::select('id')->where('name', 'SEARCH_STRING')) // score = 3
    ->search(Product::select('id')->where('description', 'SEARCH_STRING')) // score = 2
    ->search(Product::select('id')->where('content', 'SEARCH_STRING')); // score = 1

Product::searchBuilder()
    // Search on a related table
    ->search(Lot::select('product_id')->where('barcode', 'SEARCH_STRING'))
    // Search on a relation of a related table
    ->search(Lot::select('product_id')->whereHas('delivery', function ($query) {
        $query->where('address', 'SEARCH_STRING');
    }))

$terms = 'foo bar baz';

Product::searchBuilder()
    ->splitTerms($terms, function (SearchBuilder $searchBuilder, string $term) {
        // Called once with $term = foo, once with $term = bar, and once with $term = baz
        return $searchBuilder->search(Product::select('id')->where('ref', $term));
    });

$results = Product::searchBuilder()
    ->search(Product::select('id')->where('ref', 'SEARCH_STRING'), score: 100)
    ->search(Product::select('id')->where('name', 'SEARCH_STRING'), score: 50)
    ->get();

$query = Product::searchBuilder()
    ->search(Product::select('id')->where('ref', 'SEARCH_STRING'), score: 100)
    ->search(Product::select('id')->where('name', 'SEARCH_STRING'), score: 50)
    ->getQuery();