Hello readers, am back with another tutorial to discuss about performing Create Read Update Delete(CRUD) operations in laravel using ajax.
In previous tutorials like integrating bootgrid plugin there are CRUD operations but they are without ajax, every time the operation is performed the page may reload and show the information. But here all the CRUD operations are performed without any page reload by using ajax and some handy jquery.
Here we will go through a simple example to cover all the CRUD operations.
- Create operation : A simple text field to add some name and save to database.
- Read Operation : Shows all the created items which are stored in database.
- Update Operation : Edits an item which is displayed and then updating the same to database.
- Delete Operation : Delete an item completely from database.
Create Operation using ajax :
A simple text field with add button which is an ajax call to a controller.
The controller validates the input and throws an error if input is empty else it adds a new record in database.
The ajax success function updates the view by appending the newly added data to the existing data.
View for the text field and button,
When add button is clicked, an ajax call is made to the controller for adding an item.
the route for
The controller logic for addItem function,
Read Operation using ajax :
A table which displays all the records in the database with edit and delete action buttons, and also updates the data when a new item is added.
The controller logic for readItems function,
The view for displaying data,
Update Operation using ajax :
When edit button is clicked, then a modal pops up, enabling to edit the name and update button calls a controller with edit operation performed.
Here we use same modal for edit and delete operations by changing the content in it with respect to what button is clicked.
When edit button is clicked, the following jQuery is executed,
Above code opens up a modal with id and a name which can be edited with update and close buttons. When update button is clicked the logic for updation is performed.
the controller logic when /editItem is called,
Delete Operation using ajax :
Similar to edit operation. when delete button is clicked with its respected row, a modal pops up, and the delete button in the modal deletes the item from database and finally updating the view using jQuery.
When delete button is clicked, the following jQuery executes,
When delete button in the modal is clicked,
the controller logic for deletion,
Code Explanation Video: