Jquery autocomplete from database in Laravel

JQuery Autocomplete from database

In many cases, we need autocomplete fields that helps to search records. This is helpful when we have to suggest users about the possible results and prevent errors. The autocomplete also helps to speed up certain processes with more accuracy.

There are various methods to implement this. In this article, we will implement Jquery autocomplete in our laravel 5 project for searching users record. We will search through email or name of user in database.

Let’s get started writing our code.

Database Seeding

After the fresh istallation of laravel project, we get default model and migration for users table. We will seed some data in our users table. For this we will use tinker. You can also read about how to use Tinker in Laravel Application on this link.

Run the below command:

Create Routes

We will add two routes. The First route is used for displaying form to the user. The second one is important as this will be used to search the data from Database.

Create Controller

We need a new controller to process our logic. This controller will get the search term from frontend, search the user in database and return back to frontend. To create a controller through artisan command:

After this, we add some logics and our final controller file looks like below:

Create View

Our final step will be to create blade file for frontend. For frontend, we have made a small changes for importing jquery and jquery-ui files.

Now, our actual blade file is below. In this blade file, we will send a request to the server as the user types certain terms. Our final blade looks like below:

Test

When we navigate to our route, we will get as below screenshot.
laravel autocomplete from database using Jquery

Conclusion

This is all about jquery autocomplete in our Laravel application. In overall, we have seeded our database, added routes, created controller and view. When typing, on every key up event, we will send a request to the server. Server will look for the term and return accordingly.

If you have any questions or feedback regarding this article, please drop a comment below. If you like it, don’t forget to share it.