Search Through Models with Laravel Searchable
Published on by Paul Redmond
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:
use Spatie\Searchable\Search;$searchResults = (new Search())->registerModel(User::class, 'name')->registerModel(BlogPost::class, 'title')->search('john');// Total results count$searchResults->count();// Get results grouped by type$searchResults->groupByType();
You can even search for something in multiple columns within a model:
$searchResults = (new Search())->registerModel(User::class, 'first_name', 'last_name')->search('john');// Or an array of model attributes$searchResults = (new Search())->registerModel(User::class, ['first_name', 'last_name'])->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.