PHP code example of fynduck / laravel-searchable

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

    

fynduck / laravel-searchable example snippets


use Fynduck\LaravelSearchable\src\Searchable;

class User extends \Eloquent
{
    use Searchable;

     /**
     * Searchable rules.
     * Columns and their priority in search results.
     * Columns with higher values are more important.
     * Columns with equal values have equal importance.
     * @var array
     * @return array
     */
    protected function toSearchableArray()
    {
        return [
            'columns' => [
                'name'  => 10,
                'email' => 5,
            ],
             'joins' => [
                 'posts' => ['users.id','posts.user_id'],
             ],
        ];
    }

    /**
     * Select fields
     * @return array
     */
    public function selectFields()
    {
        return [
            'users.name',
            'users.email'
        ];
    }
    
    public function posts()
    {
        return $this->hasMany('Post');
    }

}

// Simple search
$users = User::search($query)->get();

// Search and get relations
// It will not get the relations if you don't do this
$users = User::search($query)
            ->with('posts')
            ->get();

// Search with relations and paginate
$users = User::search($query)
            ->with('posts')
            ->paginate(20);

// Search only active users
$users = User::where('status', 'active')
            ->search($query)
            ->paginate(20);

// Search with lower relevance threshold
$users = User::where('status', 'active')
            ->search($query, 0)
            ->paginate(20);

// Prioritize matches containing "John Doe" above matches containing only "John" or "Doe".
$users = User::search("John Doe", null, true)->get();

// Do not User::search("John Doe", null, true, true)->get();