0

I am trying to implement spatie searchable in my project and it is working fine when I am doing plain searches. But if I try to do some filtering it is not working and I have no idea though. I have added my code below:

My controller:

<?php

namespace App\Http\Livewire\SuperAdmin;

use Livewire\Component;
use Spatie\Searchable\Search;
use App\Models\Category;

class SuperAdminSearch extends Component
{
    public $query;
    public $searchResults = [];
    public $name = [];

    public function updated($property) {
        $this->name = $this->categoryName();
        if($property == 'query') {
            $searchterm = $this->query;
 
            $this->searchResults = (new Search())
                        ->registerModel(Category::class, 'name')
                        ->perform($searchterm);
        }

        if(empty($this->query)) {
            $this->searchResults = [];
        }
    }


    public function render()
    {
        return view('livewire.super-admin.super-admin-search');
    }
}

my model:

protected $fillable = ['name', 'category_type'];
public function getSearchResult(): SearchResult
{
    $url = route('super_admin_category_details', $this->id);

    return new SearchResult(
        $this,
        $this->name,
        $url
    );
}

Now what I want to do is I want to display all the category names where category_type will be ADVERTISEMENT. that's all. But I stuck for this last few days.

Thank you

apokryfos
  • 38,771
  • 9
  • 70
  • 114
ash
  • 11
  • 3

1 Answers1

0

You have to use SearchAspect. This way you can also search for exact matches and even filter your query like you would using the query builder.

    $searchResults = (new Search())
    ->registerModel(Category::class, function (ModelSearchAspect $modelSearchAspect) {
        $modelSearchAspect
        ->addSearchableAttribute('category_name')
        ->where('category_type', 'your_category_type_id');
    })->perform($searchterm);
iAmBorgy
  • 73
  • 9