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