Multiple Models Search: into One Collection with Pagination

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:

finished result


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:

seeded data

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...

The full tutorial [5 mins, 961 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 66 courses (1167 lessons, total 43 h 18 min)
  • 88 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses