Hi All, this is Adi.
I wanted to share with you my simple solution for searching, filtering & sorting data in Laravel.

The final widgetHere’s an image of what we are going to build. The first input is for searching, the second input is to select the column to order by, third is to select how to sort and last we have a dropdown to choose how many items we want in a page.

This was a widget I built for my side project - LaravelCollections.com

You can find all the code for this tutorial at this Github Gist.

TLDR;

My solution is quite simple, both the UI part and the controlling logic. The UI part is a horizontal form with GET method to the same page, this way when the Filter button is clicked, the form is redirected to the current page with each input fields as query parameters.

The logic in the controller is also quite simple. We check for these query parameters and use them to filter data from the model accordingly.

This is the gist of my solution. I go into much more detail with code examples below.

The Controller

Let’s start with the controller. The logic here is pretty simple.
Controller Logic
As you notice we initialize 4 variables with default data. Then we check if the request has any parameters if so we then set the parameters as the variables’ data.

Once we are done checking and setting the parameter, we search, sort and paginate the User model (in this case, it can be any model). Then we send the filtered data to the View along with other variables.

I’ll cover the search method of the User model in the next section.

The Model

Our search logic is also quite simple. The search method goes inside your User model class.
Model's search method
You can learn more about Laravel Model scopes here.

The View

Like the other parts, the view that makes all this work is also pretty simple.
View markup

We have a form with 5 elements, 1st input get the search query, 2nd selects the column to sort by, 3rd selects the order in which to sort by, 4th selects the records per page and last we have the Filter button to fire off the form request.

Conclusion

I hope you understood this not so lengthy tutorial. This is simple solutions I cooked up in minutes for a simple need I had. Hope you make use of it in your projects. If you have improvements to this code, do let me know, I would love to learn them.

Since you’re a Laravel developer, I have something to show you.
LaravelCollections.com is a site where I curate great resources for Laravel Developers, if you are interested, check it out.