Search Across Multiple Eloquent Models With Cross-Eloquent Search

Packages

September 23rd, 2021

cross-eloquent-search-featured.png

Laravel Cross-Eloquent Search is a package to search through multiple Eloquent models. This package supports sorting, pagination, scoped queries, eager load relationships, and searching through single or multiple columns:

1// Returns \Illuminate\Database\Eloquent\Collection
2Search::new()
3 ->add(Post::class, 'title')
4 ->add(Video::class, 'title')
5 ->get('howto');
6 
7// Add multiple models at once
8Search::addMany([
9 [Post::class, 'title'],
10 [Video::class, 'title'],
11])->get('howto');

Often, you'll want to paginate results, and this package makes doing so a cinch:

1Search::add(Post::class, 'title')
2 ->add(Video::class, 'title')
3 ->paginate()
4 // or
5 ->paginate(perPage: 15, pageName: 'page', page: = 1)
6 ->get('build');

The readme has tons of information about using this package that I'd recommend checking out:

  • Search through one or more Eloquent models
  • Support for cross-model pagination
  • Search through single or multiple columns
  • Order by (cross-model) columns or by relevance
  • Use constraints and scoped queries
  • Eager load relationships for each model
  • In-database sorting of the combined result
  • Zero third-party dependencies

You can learn more about this package, get full installation instructions, and view the source code on GitHub. The author of this package also wrote a blog post that goes into more detail about using this package.

Filed in:

Paul Redmond

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