Search Through Models with Laravel Searchable

Packages

October 7th, 2021

laravel-searchable-featured.png

Laravel Searchable is a package by Spatie to search through models and other sources pragmatically. Using this package, you can get structured results back from multiple Eloquent models. Here's an example from the README, which performs a search term against various models:

1use Spatie\Searchable\Search;
2 
3$searchResults = (new Search())
4 ->registerModel(User::class, 'name')
5 ->registerModel(BlogPost::class, 'title')
6 ->search('john');
7 
8// Total results count
9$searchResults->count();
10 
11// Get results grouped by type
12$searchResults->groupByType();

You can even search for something in multiple columns within a model:

1$searchResults = (new Search())
2 ->registerModel(User::class, 'first_name', 'last_name')
3 ->search('john');
4 
5// Or an array of model attributes
6$searchResults = (new Search())
7 ->registerModel(User::class, ['first_name', 'last_name'])
8 ->search('john');

This package provides a flexible API that enables you to customize how you search models, and even define custom search aspects, such as searching an API instead of a model.

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.