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:
Each table has its Eloquent model, and we want to query those tables and get results like this:
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?
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();56return view('search', compact('results'));
And then in the Blade, you just show three...