Search Through Models with Laravel Searchable


October 7th, 2021


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;
3$searchResults = (new Search())
4 ->registerModel(User::class, 'name')
5 ->registerModel(BlogPost::class, 'title')
6 ->search('john');
8// Total results count
11// Get results grouped by type

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');
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.

Laravel News Partners