Skip to main content
Back to packages
1,130 GitHub stars

protonemedia/laravel-cross-eloquent-search

View on GitHub

Description

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single or multiple columns

Start your search query by adding one or more models to search through. Call the add method with the model's class name and the column you want to search through. Then call the search method with the search term, and you'll get a \Illuminate\Database\Eloquent\Collection instance with the results.

The results are sorted in ascending order by the updated column by default. In most cases, this column is updated_at. If you've customized your model's UPDATED_AT constant, or overwritten the getUpdatedAtColumn method, this package will use the customized column. If you don't use timestamps at all, it will use the primary key by default. Of course, you can order by another column as well.

use ProtoneMedia\LaravelCrossEloquentSearch\Search;
 
$results = Search::add(Post::class, 'title')
->add(Video::class, 'title')
->search('howto');

If you care about indentation, you can optionally use the new method on the facade:

Search::new()
->add(Post::class, 'title')
->add(Video::class, 'title')
->search('howto');

There's also a when method to apply certain clauses based on another condition:

Search::new()
->when($user->isVerified(), fn($search) => $search->add(Post::class, 'title'))
->when($user->isAdmin(), fn($search) => $search->add(Video::class, 'title'))
->search('howto');

In addition, you can use the tap method to tap into the searcher instance:

Search::add(Post::class, 'title')
->add(Video::class, 'title')
->tap(function ($searcher) {
Log::info('Search configuration', ['models' => $searcher->getModelsToSearchThrough()]);
})
->search('laravel');

Related Content on Laravel Daily

Video

Recent Courses on Laravel Daily

Laravel 13 Eloquent: Expert Level

41 lessons
1 h 34 min

How to Build Laravel 13 API From Scratch

30 lessons
1 h 23 min

How to Structure Laravel 13 Projects

16 lessons
1 h 32 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.