Laravel Packages

Search Through Models with Laravel Searchable

Published
Search Through Models with Laravel Searchable image

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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article