PHP code example of masterro / laravel-searchable

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

    

masterro / laravel-searchable example snippets


MasterRO\Searchable\SearchableServiceProvider::class

Searchable::registerModels([
    Post::class,
    Article::class,
    User::class,
]);

public static function searchable(): array
{
    return ['title', 'description'];
}

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();

            $table->string('title');
            $table->longText('description');
            $table->dateTime('published_at')->nullable();

            $table->timestamps();
        });

        DB::statement('ALTER TABLE posts ADD FULLTEXT search(title, description)');
    }

public function search(Request $request, Searchable $searchable)
{
    $query = trim($request->input('q'));

    if (mb_strlen($query) < 3) {
        return back()->withInput()->withErrors([
            'search_error' => __('messages.search_error')
        ]);
    }
    
    return view('search.index')->with('results', $searchable->search($query));
}

$result = $this->searchable->searchModel(Post::class, 'consequatur');

$result = $this->searchable->searchModel([Article::class, Post::class], 'consequatur');

class User extends Model implements SearchableContract
{
    public function posts() {
        return $this->hasMany(Post::class);
    }

    public function filterSearchResults($query) {
        return $query->whereHas('posts', function ($query) {
            $query->where('is_published', true);
        });
    }
}

$result = $this->searchable
    ->withFilter(function (Builder $query) {
        return $query->getModel() instanceof Post
            ? $query->where('description', '!=', 'Doloremque iure sequi quos sequi consequatur.')
            : $query;
    })
    ->search('Dolorem');

$result = $this->searchable->withoutModelFilters()->search('quia est ipsa molestiae hic');

$result = $this->searchable
    ->withoutModelFilters(Post::class)
    ->search('quia est ipsa molestiae hic');

$result = $this->searchable
    ->withoutModelFilters([Article::class, Post::class])
    ->search('quia est ipsa molestiae hic');

$result = $this->searchable
    ->with([Article::class => 'author'])
    ->search('consequatur');

$result = $this->searchable
    ->with([
        Article::class => [
            'author' => function ($query) {
                return $query->where('active', true);
            },
        ],
    ])
    ->searchModel(Article::class, 'consequatur');