Skip to main content
Back to packages
1,371 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.

Recent Courses on Laravel Daily

Next.js Basics for Laravel Developers

11 lessons
58 min

Roles and Permissions in Laravel 13

14 lessons
57 min

Queues in Laravel 13

18 lessons
1 h 12 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.