In this tutorial, we will create a simple search from three Models and will use Laravel Collections to combine them into one collection to show results in the front-end.
Also, we will make the table row background color to be based on the Model. And finally, we will add pagination to the Collection to show results with the pagination links.
In the end, we will have a similar result to this:

The structure of the database here is very simple. We have three models Post, Video, and Course, and each has a title column. Seeded data would look similar to this:

Now for the controller where the search happens. In the search form, input has the name of query and because the form uses the GET method, after submitting the form we are getting to URL similar to /search?query=. In the controller, we can get the query parameter using Request. Using all of this, we can search this:
use Illuminate\Http\Request; class SearchController extends Controller{ public function __invoke(Request $request) { $posts = Post::where('title', 'like', '%' . $request->input('query') . '%')->get(); $courses = Course::where('title', 'like', '%' . $request->input('query') . '%')->get(); $videos = Video::where('title', 'like', '%' . $request->input('query') . '%')->get(); }}
Now that we have all results...
Premium Members Only
This advanced tutorial is available exclusively to Laravel Daily Premium members.
Already a member? Login here
Premium membership includes:
This is good and works, but has one downside, that it loads all the data in the memory. It somewhat defeats the purpose of pagination, and has a performance penalty at larger datasets.
Any idea/tip about how to only load the records that are needed for the current page?
We're running a few ideas, but maybe you also have one - it worth a question :)
Yes, I agree that it loads all the data. Well, you can load not all the data, but only 10 records from each type, for example, where 10 is max records per page you would show anyway.
But generally, there's no universal good solution for this, at least I haven't experienced it.
thanks a lot, have you a repo for this ?
This package does way more than just "zipping" multiple model types, but it does the job quite well: https://github.com/protonemedia/laravel-cross-eloquent-search