Skip to main content
Premium Members Only
Join to unlock this tutorial and all of our courses.
Tutorial Premium Tutorial

Laravel Multiple Model Search: Queries, Scout, Packages

December 15, 2022
9 min read

If you want to search in multiple Eloquent models - like posts, videos, and courses - there are a lot of different ways, with or without external packages and tools. Let's explore them in this article.

First, the example we will be working on. Three simple DB tables:

  • posts
  • videos
  • courses

Global search - table 1

Global search - table 2

Global search - table 3

Each table has its Eloquent model, and we want to query those tables and get results like this:

Global search - results

So, what are our options? Let's go from the most simple one to adding more tools later.


Simple: Three Separate Queries

This is the most straightforward, almost "dumb" way to perform the task. Why group or optimize something, if you can just query the tables separately?

Controller:

1$keyword = request('keyword');
2$results['posts'] = Post::where('title', 'like', '%' . $keyword . '%')->get();
3$results['videos'] = Video::where('title', 'like', '%' . $keyword . '%')->get();
4$results['courses'] = Course::where('title', 'like', '%' . $keyword . '%')->get();
5 
6return view('search', compact('results'));

And then in the Blade, you just show three...

Premium Members Only

This advanced tutorial is available exclusively to Laravel Daily Premium members.

Premium membership includes:

Access to all premium tutorials
Video and Text Courses
Private Discord Channel

Comments & Discussion

W
wolfatadfilm ✓ Link copied!

Just a minor point, but for clarity: when you use Laravel Scout with database driver, after publishing the assets you also need to edit the config/scout.php to change from Algolia to database driver

PK
Povilas Korop ✓ Link copied!

Thanks a lot for the correction, added to the article!

N
Nouar ✓ Link copied!

Very nice tutorial

J
j.kludt ✓ Link copied!

https://laravel-news.com/laravel-scout-practical-guide

Example for SCOUT search with relationship!

RM
Rui Miguel Tavares Costa ✓ Link copied!

I liked you 3 queries, but, how to paginate all those results?

N
Nerijus ✓ Link copied!

Try passing different pageName in the paginate() method. And when using links(). Don't forget to use withQueryString().