Coder Social home page Coder Social logo

laravel-searchable's Introduction

Laravel Searchable

Latest Version on Packagist run-tests Total Downloads

This package makes it easy to get structured search from a variety of sources. Here's an example where we search through some models. We already did some small preparation on the models themselves.

$searchResults = (new Search())
   ->registerModel(User::class, 'name')
   ->registerModel(BlogPost::class, 'title')
   ->search('john');

The search will be performed case insensitive. $searchResults now contains all User models that contain john in the name attribute and BlogPosts that contain 'john' in the title attribute.

In your view you can now loop over the search results:

<h1>Search</h1>

There are {{ $searchResults->count() }} results.

@foreach($searchResults->groupByType() as $type => $modelSearchResults)
   <h2>{{ $type }}</h2>
   
   @foreach($modelSearchResults as $searchResult)
       <ul>
            <li><a href="{{ $searchResult->url }}">{{ $searchResult->title }}</a></li>
       </ul>
   @endforeach
@endforeach

In this example we used models, but you can easily add a search aspect for an external API, list of files or an array of values.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-searchable

Usage

Preparing your models

In order to search through models you'll have to let them implement the Searchable interface.

namespace Spatie\Searchable;

interface Searchable
{
    public function getSearchResult(): SearchResult;
}

You'll only need to add a getSearchResult method to each searchable model that must return an instance of SearchResult. Here's how it could look like for a blog post model.

use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;

class BlogPost extends Model implements Searchable
{
     public function getSearchResult(): SearchResult
     {
        $url = route('blogPost.show', $this->slug);
     
         return new \Spatie\Searchable\SearchResult(
            $this,
            $this->title,
            $url
         );
     }
}

Searching models

With the models prepared you can search them like this:

$searchResults = (new Search())
   ->registerModel(User::class, 'name')
   ->search('john');

The search will be performed case insensitive. $searchResults now contains all User models that contain john in the name attribute.

You can also pass multiple attributes to search through:

// use multiple model attributes

$searchResults = (new Search())
   ->registerModel(User::class, 'first_name', 'last_name')
   ->search('john');
   
// or use an array of model attributes

$searchResults = (new Search())
   ->registerModel(User::class, ['first_name', 'last_name'])
   ->search('john');

To get fine grained control you can also use a callable. This way you can also search for exact matches, apply scopes, eager load relationships, or even filter your query like you would using the query builder.

$search = (new Search())
   ->registerModel(User::class, function(ModelSearchAspect $modelSearchAspect) {
       $modelSearchAspect
          ->addSearchableAttribute('name') // return results for partial matches on usernames
          ->addExactSearchableAttribute('email') // only return results that exactly match the e-mail address
          ->active()
          ->has('posts')
          ->with('roles');
});

Creating custom search aspects

You are not limited to only registering basic models as search aspects. You can easily create your own, custom search aspects by extending the SearchAspect class.

Consider the following custom search aspect to search an external API:

class OrderSearchAspect extends SearchAspect
{
    public function getResults(string $term): Collection
    {
        return OrderApi::searchOrders($term);
    }
}

This is how you can use it:

$searchResults = (new Search())
   ->registerAspect(OrderSearchAspect::class)
   ->search('john');

Limiting aspect results

It is possible to limit the amount of results returned by each aspect by calling limitAspectResults prior to performing the search.

$searchResults = (new Search())
    ->registerAspect(BlogPostAspect::class)
    ->limitAspectResults(50)
    ->search('How To');

Rendering search results

Here's an example on rendering search results:

<h1>Search</h1>

There are {{ $searchResults->count() }} results.

@foreach($searchResults->groupByType() as $type => $modelSearchResults)
   <h2>{{ $type }}</h2>
   
   @foreach($modelSearchResults as $searchResult)
       <ul>
            <a href="{{ $searchResult->url }}">{{ $searchResult->title }}</a>
       </ul>
   @endforeach
@endforeach

You can customize the $type by adding a public property $searchableType on your model or custom search aspect

class BlogPost extends Model implements Searchable
{
    public $searchableType = 'custom named aspect';
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-searchable's People

Contributors

adrianmrn avatar alexvanderbist avatar amaelftah avatar freekmurze avatar grantholle avatar hexnet avatar jadsalhani avatar jamesfreeman avatar ju5t avatar laravel-shift avatar larsjanssen6 avatar lusitaniae avatar mojtabaahn avatar netpok avatar officialkidmax avatar owenvoke avatar patinthehat avatar povilaskorop avatar riasvdv avatar samuelnitsche avatar shuvroroy avatar socoladaica avatar timacdonald avatar voydz avatar walrussoup avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-searchable's Issues

Problem with search string...

I have registered model to being searchable throw the string. An example I have two users name 'JOHN NILSON' & 'DOE NILSON' when I am typing a single word in search area like 'john 'then its return JOHN, perfect results, but when I use spaces in search string like 'john doe' then it is returning both JOHN & DOE.
as per my query, I need only the results with JOHN DOE.
how can it be done?

1.6.2 breaks search with PostgreSQL

Hello,

It seems that 1.6.2 escaping change (1.6.1...1.6.2) broke search with PostreSQL 10. Example error:

Sample error:

SQLSTATE[42883]: Undefined function: 7 ERROR:  operator does not exist: ` character varying\nLINE 1: select * from \"restaurants\" where (LOWER(`name`) LIKE $1 or ...\n                                                 ^\nHINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts. (SQL: select * from \"restaurants\" where (LOWER(`name`) LIKE %mor% or LOWER(`email`) LIKE %mor% or LOWER(`phone`) LIKE %mor%) and \"restaurants\".\"deleted_at\" is null limit 5)",

Thanks for this package.

is it possible to display eager loading result

I want to display has many relationship results.

i have a tables "authors" and "articles" with belongsToMany relation.

if I search with author name, should display the related articles ( one author can writes many articles ).

i have tried with custom search aspects but not succeed. got the below error

Declaration of App\ContributorSearch::getResults(string $term): App\Collection must be compatible with Spatie\Searchable\SearchAspect::getResults(string $term): Illuminate\Support\Collection

Passing searchable attributes as array does not work

When I pass the searchable attributes as an array (like in the examples) the following error is thrown:
Argument 1 passed to Spatie\\Searchable\\SearchableAttribute::__construct() must be of the type string, array given

Code looks like this:

$searchResults = (new Search())
            ->registerModel(Ticket::class, ['title', 'body', 'from_address', 'from_name'])
            ->perform(request('q'));

This works:

$searchResults = (new Search())
            ->registerModel(Ticket::class, 'title', 'body', 'from_address', 'from_name')
            ->perform(request('q'));

Search polymorphic relations (tags)

Hello ! I am using another great Spatie's package : spatie/laravel-tags

As you may know, this package adds tags to the models, just like this, using polymorphic relationship :

Taggables

  • tag_id
  • taggable_type
  • taggable_id

Tags

  • id
  • name (json datatype for translations)
  • slug
  • type
    [...]

I was wondering how to implement the search on models with tags ?
I tried using ModelSearchAspect, but I couldn't succeed. Any leads on how to make this work ?

Thanks by advance, and thanks to Spatie for these great packages ! 😁 👍

How can I add order by column attribute?

Hello,

I want to add 'orderBy' column in the search results.
I have added the value like this below in __construct function in 'SearchResult' class, but it need to set up more.

/** @var string */
    public $reg_time;

    public function __construct(Searchable $searchable, string $title, ?string $url = null, string $reg_time)
    {
        $this->searchable = $searchable;

        $this->title = $title;
        $this->url = $url;
        $this->reg_time = $reg_time;
    }

Where can I add it?

Wrong method name in examples

In the examples the mentioned method to perform the actual search is called search. In the code the method is called perform.

Pagination on search results

It would be awesome, if the results on searchable query provide a function just like ->paginate(int) on collections to be more effective when the search has multiple models.

$searchType is not being set

Even though I set static $searchType = 'Some name'; it is not being set in the type-property of the SearchResult.

I am not using a custom search aspect, but instead just a normal model class. Then I am displaying it using the example in the docs: $searchResults->groupByType()

Search on Json fields

Hi,
I have an issue with searching on json fields,

$searchResults = (new Search())
            ->registerModel(Document::class, ['title', 'body', 'sender->title'])
            ->registerModel(Inbox::class, 'document_reference')
            ->perform($search);

sender is a field that have a property named title and I want search on it,

How should i do this? did you handle json search ?

Thanks in advance

Unique search results in SearchResult object

I have a model for each inputfield (title, body, summary) of an article and all those fields should be searchable. All these inputfields have a relationship, because they are part of an article page. The search works but I get multiple results for the same article (page), if several model includes the search term.

For example: searchterm = English

  1. Title: How to learn English
  2. Summary: A page about how to learn English
  3. Body: English is a language.......

So the searchterm "English" can be found in all those tables (models). In this case my Spatie\Searchable\SearchResult object returns 3 times the same article as a search result (one for each model).

Screenshot

Is there a simple way to make the search results unique to prevent multiple results from the same page (same URL).

Best regards

use this with strict match result

hello,

Is it possible to use this with strict matching results :
exemple:
User::where('name', '=', "%{$term}%")->get();

instead of this:
User::where('name', 'LIKE', "%{$term}%")->get();

thanks

Searching related models

Great package! Love it so far.

Is it possible to search related models? For example, a UserProfile model but search through User? I want to display the profile results as part of the search in the User type? In other words, I'd search user_biography in UserProfile but will want to display the results grouped in User results in case they search username.

Possible?

Ability to extend SearchResult

It would be nice if it were possible to replace or extend SearchResult class because sometimes I need to have additional properties besides title and url.
Do you have plans for this?

Relationship Issues

After Bring Search Result , using with to bring both the relationship not working

Registering an attribute with the same name as a global method can cause unexpected behavior

When registering my Article-model, I want it to search using the attribute title.

$searchResults = (new Search())
        ->registerModel(Article::class, 'title')
        ->search('a');

I have a global helper method called title(). Doing this, somehow triggers the global title()-method end throws an error: Object of class Spatie\Searchable\ModelSearchAspect could not be converted to string.

The error is not really relevant, but what happens is that it calls the title()-method with itself. This is what triggers it: ModelSearchAspect.php:50

if (is_callable($attributes)) {
        $callable = $attributes;

        $callable($this);
    }

Searching the model and relations

Is it possible to search the model and the relations of the model?
for example:
Search term = "Red T-Shirt"
Model: Product
Relations: Categories, tags
search columns product.name, Categories.name and tags.name

Struggling with aspects

I am trying to come up with a solution for the explode() happening in ModelSearchAspect's addSearchConditions(). I would like to search for 'hello world' instead of 'hello' and 'world' which is the current functionality.

I tried creating my own aspect.

<?php

namespace App\Search;

use Illuminate\Database\Eloquent\Builder;
use Spatie\Searchable\ModelSearchAspect;

class FullSearchAspect extends ModelSearchAspect
{
    protected function addSearchConditions(Builder $query, string $term)
    {
        $attributes = $this->attributes;

        $query->where(function (Builder $query) use ($attributes, $term, $searchTerms) {
            foreach (Arr::wrap($attributes) as $attribute) {
                $sql = "LOWER({$attribute->getAttribute()}) LIKE ?";
                $searchTerm = mb_strtolower($term, 'UTF8');

                $attribute->isPartial()
                    ? $query->orWhereRaw($sql, ["%{$term}%"])
                    : $query->orWhere($attribute->getAttribute(), $term);
            }
        });
    }
}

And the following snippet is responsible for search:

class SearchController extends Controller
{
    public function search(Request $request, $search)
    {
        $searchResults = (new Search())
            ->registerAspect(FullSearchAspect::class)
            ->registerModel(Article::class, function (FullSearchAspect $modelSearchAspect) {

This gives me an error:

Unresolvable dependency resolving [Parameter #0 [ <required> string $model ]] in class Spatie\Searchable\ModelSearchAspect

I guess this happens because I don't understand aspects yet. I think I need to override Search() too and override registerModel to use my aspect (or add a new method).

What do you suggest?

search with 2 words keyword?

I have a user model with first_name and last_name. If I search the keyword first_name or last_name works fine. But is it possible to match by searching the full name?

Ex: John is first_name, Doe is the last_name. If I search 'John' or 'Doe' it's returning as properly as expected. But if my keyword is 'John Doe', it's returning empty.

Enable Package Discovery?

Greetings!

Just wanted to see if your open to a pull request to enable package auto discovery? If not, no big deal.

Cheers,

  • Wyatt

Escape search attributes

Hi there,

first of all: thank you for making awesome contributions to the open source community. And thank you for this great package. Fiddeling around with it since only a few minutes and the results are fantastic!

Though I might have found a little issue (which in the end is caused by me). I got a model with an attribute of key (yes, now I remembered.. its a reserved mysql keyword.. 😂). Using this attribute as a searchable attribute while registering a model I get a mysql syntax error. The error points me to a raw query here. I noticed that the attribute is not string-escaped. To conclude:

Reproducable by

$searchResults = (new Search())
   ->registerModel(Device::class, 'key') # or any other mysql keyword
   ->search('A100');

Expected behavior
Return my search results.

Actual behavior
MySQL syntax error.

Workaround
Since the string is passed through a workaround (string-escape) is quite simple:

$searchResults = (new Search())
   ->registerModel(Device::class, '`key`') # note the ``
   ->search('A100');

I totally get that naming attributes like mysql reserved keywords is not the best idea. (And in fact I will refactor my application to accommodate for that.) But I guess, since it is a quite simple change and would make it work without any downsides it could at least be considered.

P.S. If I find the time I might submit a PR for this.

EDIT: For reference I found an old PR targeting the same issue #42

More fields in search result

Hello,
I'm trying to search in blog posts and show more fields than title, url. For example, I want to show post thumb, category. How do I do that?

Here is my custom search aspect

public function getResults(string $term): Collection
    {
        return Post::query()
            ->where('status', true)
            ->where('title', 'LIKE', "%{$term}%")
            ->with('cat')
            ->get();
    }

Regards

syntax error, unexpected ')' on Model Function

Hi, I used this library on my local project and it works but when I uploaded on a server i have this error :
Symfony\Component\Debug\Exception\FatalThrowableError
syntax error, unexpected ')'

`<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

use Spatie\Searchable\Searchable;

use Spatie\Searchable\SearchResult;

class TusProgram extends Model implements Searchable

{

public function getSearchResult(): SearchResult

{

    return new \Spatie\Searchable\SearchResult(

        $this,
         program_name,
        '/academics/tus',

);

}

}`

Load Relationships table

Hey there ,
I'm using laravel voyager as admin package and spatie/laravel-searchable as search engine.
i'm building app with 5 languages so i need to make search title for these languages.
In my Tutorial Model

public function getSearchResult(): SearchResult
  {
      $url = route('tutorial', $this->slug);

      return new \Spatie\Searchable\SearchResult(
          $this,
          $this->title,
          $url
       );
  }

In My Search Controller :

public function search(Request $request)
  {
      $searchterm = $request->input('query');
      $searchResults = (new Search())
          ->registerModel(Tutorial::class, 'title')
          ->perform($searchterm);

      return view('search.show', compact('searchResults', 'searchterm'));
  }

My View:

@foreach($searchResults->groupByType() as $type => $modelSearchResults)
                <h2>{{ ucfirst($type) }}</h2>
         @foreach($modelSearchResults as $searchResult)
                <ul>
                    <li><a href="{{ $searchResult->url }}">{{ $searchResult->title }}</a></li>
                </ul>
          @endforeach
@endforeach

And my form input :

<form action="{{ route('search') }}" method="GET">
      @csrf
      <input class="form-control searchBar" type="text" placeholder=" 
            {{__('home.search_placeholder')}}"
            aria-label="Search" name="query" value="{{ request($query ?? '') }}" />
 </form>

spatie laravel-searchable only find English(default language) title and nothing for the other languages.

I'm maybe missing something .
Thank you for your help

search deep related models

Hi. I've been working some projects and it has deep relationship eloquent models. I've read the readme how to create custom search by our own. Unfortunately, i can't solve it. I hope you could help.
Here's my relationship models

version -> activity_type -> activity -> category -> notes -> sub1notes -> sub2notes

The eloquent is dependent by their id. I want to search string in all of those models inside the version tables which the version.status is active. I've tried to build custom search but it always shows all of the datas without filter the active version. Please help. Thank you.

Additional search condition

I'm using this plugin for couple of months and it's working fine.
As a new task in one of my projects, an additional condition to the search.

So, my idea is if a user is blocked (it has status == 0) to not be displayed in the search result.

This is my code:

PageController:

public function searchMember(Request $request, $id)
    {

      $this->validate($request, [
        'query' => 'required',

      ]);

      $query = $request->input('query');

      $searchResults = (new Search())
          ->registerModel(User::class, 'first_name', 'last_name')
          ->perform($query);

      return view('user.search', compact('searchResults'));

    }

View:

<div class="result-count">{{ $searchResults->count() }} results found for "{{ request('query') }}"</div>
<div class="result">
  @foreach($searchResults->groupByType() as $type => $modelSearchResults)
    @foreach($modelSearchResults as $searchResult)
        <div class="article">
          <a href="{{ $searchResult->url }}">{{ $searchResult->title }}</a>
        </div>
    @endforeach
  @endforeach
</div>

It works fine but I want to add where() parameter, so I can display only active users (status 1).
I've read if I want to add conditions, I have to tweak the code and I've tried like this in my controller:

public function searchMember(Request $request, $id)
{

  $this->validate($request, [
    'query' => 'required',

  ]);

  $searchResults = (new Search())
     ->registerModel(User::class, function(ModelSearchAspect $modelSearchAspect) {
         $modelSearchAspect
            ->addSearchableAttribute('first_name')
            ->addSearchableAttribute('last_name')
            ->where('status', 0); // This won't work
     })->search($request->input('query'));

  return view('user.search', compact('searchResults'));

}

Of course, Im getting this error: Call to undefined method because I don't have that method available.

How can I add that condition?

Extra ModelSearchAspect features

I might be nice to add a couple of extra helpers to the ModelSearchAspect.

For example:

  • relationship support, including eager loading relations (#8 and #14)
  • scope support: $modelSearchAspect->addSearchableScope($scopeName) (#9)
  • pagination #20

Prioritize results

Hi,

the package is really useful, one of the features I was looking for was to split the term, etc... congratulations.

Have you thought on adding sort support, like put on top the most similar result to the term?

I would think like using similar_text or levenshtein PHP functions to achieve this.

Searching in numeric fields with PostgreSQL throws an exception with LOWER() function

Hello,
Using spatie/laravel-searchable version 1.3.0 with PostgreSQL 11, I'm getting an exception SQLSTATE[42883]: Undefined function: 7 ERROR: function lower(bigint) does not exist.
MySQL allows using lower on integers but PostgreSQL has strict typing on its functions and the only prototype is lower(text). Is it possible to typecheck the field and use lower only where it makes sense?

All the Attibutes came back null

Spatie\Searchable\SearchResultCollection {#204 ▼
  #items: array:1 [▼
    0 => Spatie\Searchable\SearchResult {#345 ▼
      +searchable: App\Account {#364 ▶}
      +account_number: null
      +firstname: null
      +lastname: null
      +residential_address: null
      +office_address: null
      +business_type: null
      +created_on: null
      +url: "//localhost:3000/account/clients/AC9595676"
      +type: "accounts"
    }
  ]
}

Here is my code, which is literaly what I copied in the docs

            $results = (new Search())
               ->registerModel(Account::class, function(ModelSearchAspect $modelSearchAspect) {
                   $modelSearchAspect
                      ->addExactSearchableAttribute('account_number')
                      ->addSearchableAttribute('firstname')
                      ->addSearchableAttribute('lastname')
                      ->addSearchableAttribute('residential_address')
                      ->addSearchableAttribute('office_address')
                      ->addSearchableAttribute('business_type')
                      ->addSearchableAttribute('created_on')
                      ->with('current_marketer');
            })->search($request->input('q'));

How do I proceed? How do I get the result. the attributes in the Searchable key displays a model matching my search but how do I display it in my blade files

Backticks used in Spatie\Searchable\ModelSearchAspect::addSearchConditions() are not supported by PostgreSQL

Queries containing backticks (`) work in MySQL to quote system identifiers, but they will cause PostgreSQL to choke. Example:

select * from users where (LOWER(`full_name`) LIKE '%foo%' or /* ... */ )

Works in MySQL (presumably) but Postgres doesn't like this. Instead we get the following Exception:

Illuminate/Database/QueryException with message 'SQLSTATE[42883]: Undefined function: 7 ERROR:  operator does not exist: ` character varying
LINE 1: select * from "users" where (LOWER(`full_name`) LIKE $1 or L...
                                           ^
HINT:  No operator matches the given name and argument type. You might need to add an explicit type cast. (SQL: select * from "users" where (LOWER(`full_name`) LIKE %foo% or LOWER(`email`) LIKE %foo%) and "users"."deleted_at" is null)'

The main place I found this issue was in Spatie\Searchable\ModelSearchAspect::addSearchConditions() but it could be elsewhere in the code since I'm not familiar with it.

I'd like to recommend that this package accept a $connection parameter to specify which database connection to use (e.g. new Search($connection), which would default to config('database.default') if not given). Then, the above-mentioned method can decide to use backticks if the connection driver is 'mysql' and double-quotes if the connection driver is 'pgsql'. (Not sure about other database vendors.)

Additional Search Condition

Not sure if already supports but couldn't find in the doc: Way to get Search records where active is 1?

Example:

$results = (new \Spatie\Searchable\Search())
->registerModel(Listing::class, 'name')
->search($terms);

How do I add condition (if any)?
Thanks.

Adding scope to filter search results

Hi spatie,

thanks for this nice package. Loving it so far.

But I wonder, if I could add a scope like published() to the search on posts. Is that possible? Could not find a way to apply it yet.

Best regards

Chris

limit nbr of results by model type

hi every body,


public function getModelWiki()
    {
        $array = (new Search())
            ->registerModel( Ceremonie::class, 'nom')
            ->registerModel( Hopital::class, 'nom')
            ->registerModel( Cimetiere::class, 'nom')
            ->registerModel( Ville::class, 'ville')
            ->perform(request('query'));

        return response()->json($array);
    }

is there any way to limit the number of each models returned?
thx.

More than one condition (Filter)

In this package i cannot find a way to integrate more than one condition.
For example:

`<form action="{{route('search-biograph')}}" method="get">
        <input type="hidden" name="_token" value="{{csrf_token()}}">
               <div class="input-group mb-3">
                        <input type="text" class="form-control form-control-lg badge-pill" 
 placeholder="Search Bio" aria-label="search bio" aria-describedby="button- 
                                   addon2" name="query" >  {{-- form-control-lg --}}
                                <div class="input-group-append">
                                    <button class="btn btn-default  badge-pill" type="submit" id="button-addon2"> Search</button>
                                </div>
                            </div>
                            <div class="row">
                                <button type="button" class="btn btn-default btn-sm">Search</button>
                                <div class="col-2">
                                    <select class="custom-select input-" name="bio" id="inputGroupSelect01">
                                        <option value="">Biograph</option>
                                        <option value="has">Exist</option>
                                        <option value="not have">Does not exist</option>
                                    </select> 
                                </div> 
                                <div class="col-2">
                                    <select class="custom-select input-" name="age_more_than" >
                                        <option value="">age</option>
                                        <option value="1">More than  40+</option>
                                        <option value="2">Less than 40-</option>
                                    </select> 
                                </div> 
                     </div>
           </form`

fuzzy search functionality

Hello Team,
It's possible we search like " fany " word and output given me "fancy" .. ?
same like scout functionality...

SearchResultError

I keep getting this error even after going through the given steps:

"Symfony\Component\Debug\Exception\FatalErrorException: Declaration of App\Services::getSearchResult(): App\getSearchResult must be compatible with Spatie\Searchable\Searchable::getSearchResult(): Spatie\Searchable\SearchResult in file C:\Users\HP\Desktop\react-native-course-projects\Hair-app-backend\app\Services.php on line 9"

My Services Class:

`<?php

namespace App;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
use Illuminate\Database\Eloquent\Model;

class Services extends Model implements Searchable
{
protected $fillable = [
'serviceTitle', 'serviceDescription', 'serviceCost', 'serviceCategory'
];
public function getSearchResult(): getSearchResult
{
$url = '/searchResults';
return new SearchResult(
$this,
$this->serviceTitle,
$url
);
}
public function artisan() {
return $this->belongsToMany(Artisan::class);
}
}`

MY SEARCH CONTROLLER:

`<?php

namespace App\Http\Controllers;

use App\Artisan;
use App\Services;
use Illuminate\Http\Request;
use Spatie\Searchable\Search;

class SearchController extends Controller
{
public function search(Request $request)
{
$searchResults = (new Search())
// ->registerModel(Artisan::class, 'artisanTitle')
->registerModel(Services::class, 'serviceTitle')
->perform($request->get('query'));

    return response()->json([
        'searchResult'=> $searchResults
    ]);
}

}`

Eager loading relationship

I think it would be great if one could somehow eager load relationship with this package. Right now, it creates an N+1 problem.

Search Model on Appended Attribute

Hey guys,

Love the package. Question I had was whether it was possible to add a custom attribute based on a function that's not in the database.

example my Query Model has a body column which contains JSON markup for the delta text rendering. Basically it's a mix of text and transformations like this:

Query::class body column.

{"ops":[{"insert":"No power again as of 5pm\n"}]}

so say I were to register the Model, and I wanted to search the body for the word power. I'd do:

$results = (new Search())->registerModel(Query::class, 'body')->search($request->input('query'));

And that would work. However If someone were to search for the word 'insert' or something that is part of the delta syntax, it would include that in the search result.

So I have a function in my Query class called getDeltaStringAttribute() that returns the delta body in text (without the transformations). In my Query model I added 'deltaString' to my protected $appends = [] array.

Meaning in ticker and usual object references I can get call $query->deltaString; and instead of getting {"ops":[{"insert":"No power again as of 5pm\n"}]} I would get No power again as of 5pm.

Now since this column / attribute doesn't technically exist, how can I register that in my search?

->registerModel(Query::class, 'deltaString')

would not work in this fashion.

Any idea if this is possible or if I can extend it someone?

Thank you!

Does this use elasticsearch ?

It doesn't say what data sources that it supports in the documentation. Seems like an interesting/useful project. Would like to know more about details on Searching before would ever use it on a project. Thanks.

Are there any additional installation steps required?

I was wondering if there are any additional steps required in order to install this library. So I walked through the readme and used the command below:

composer require spatie/laravel-searchable

After this, I wanted to follow up with setting up my models in order to use it. When I copied the use statement from the examples in the readme, but it shows me a message that the two use statements are of an undefined namespace.

When I look in my composer.json file I can't seem to find the package anywhere. So this makes me think that something went wrong during the installation or additional steps are required.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.