Skip to main content
Back to packages
1,373 GitHub stars

spatie/laravel-searchable

View on GitHub

Description

Pragmatically search through models and other sources

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.