Ajax CRUD operations in laravel

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.
Video Explanation:
You can watch the video on Youtube here.
Working Demo Project on Github
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 the database.
- Read Operation: Shows all the created items which are stored in the database.
- Update Operation: Edits an item which is displayed and then updating the same to the database.
- Delete Operation: Delete an item completely from the 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 the input is empty else it adds a new record in the 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,
<div class="form-group row add"> <div class="col-md-8"> <input type="text" class="form-control" id="name" name="name" placeholder="Enter some name" required> <p class="error text-center alert alert-danger hidden"></p> </div> <div class="col-md-4"> <button class="btn btn-primary" type="submit" id="add"> <span class="glyphicon glyphicon-plus"></span> ADD </button> </div> </div>
When add button is clicked, an ajax call is made to the controller for adding an item.
$("#add").click(function() { $.ajax({ type: 'post', url: '/addItem', data: { '_token': $('input[name=_token]').val(), 'name': $('input[name=name]').val() }, success: function(data) { if ((data.errors)) { $('.error').removeClass('hidden'); $('.error').text(data.errors.name); } else { $('.error').remove(); $('#table').append("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.name + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.name + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.name + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>"); } }, }); $('#name').val(''); });
the route for /addItem
,
Route::post ( '/addItem', 'IndexController@addItem' );
The controller logic for addItem function,
public function addItem(Request $request) { $rules = array ( 'name' => 'required' ); $validator = Validator::make ( Input::all (), $rules ); if ($validator->fails ()) return Response::json ( array ( 'errors' => $validator->getMessageBag ()->toArray () ) ); else { $data = new Data (); $data->name = $request->name; $data->save (); return response ()->json ( $data ); } }
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 route,
Route::get ( '/', 'IndexController@readItems' );
The controller logic for readItems function,
public function readItems(Request $req) { $data = Data::all (); return view ( 'welcome' )->withData ( $data ); }
The view for displaying data,
<div class="table-responsive text-center"> <table class="table table-borderless" id="table"> <thead> <tr> <th class="text-center">#</th> <th class="text-center">Name</th> <th class="text-center">Actions</th> </tr> </thead> @foreach($data as $item) <tr class="item{{$item->id}}"> <td>{{$item->id}}</td> <td>{{$item->name}}</td> <td><button class="edit-modal btn btn-info" data-id="{{$item->id}}" data-name="{{$item->name}}"> <span class="glyphicon glyphicon-edit"></span> Edit </button> <button class="delete-modal btn btn-danger" data-id="{{$item->id}}" data-name="{{$item->name}}"> <span class="glyphicon glyphicon-trash"></span> Delete </button></td> </tr> @endforeach </table> </div>

Working Demo Project on Github
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 the 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,
$(document).on('click', '.edit-modal', function() { $('#footer_action_button').text(" Update"); $('#footer_action_button').addClass('glyphicon-check'); $('#footer_action_button').removeClass('glyphicon-trash'); $('.actionBtn').addClass('btn-success'); $('.actionBtn').removeClass('btn-danger'); $('.actionBtn').addClass('edit'); $('.modal-title').text('Edit'); $('.deleteContent').hide(); $('.form-horizontal').show(); $('#fid').val($(this).data('id')); $('#n').val($(this).data('name')); $('#myModal').modal('show'); });
Above code opens up a modal with id and a name which can be edited with update and close buttons. When update button has clicked the logic for updating is performed.
$('.modal-footer').on('click', '.edit', function() { $.ajax({ type: 'post', url: '/editItem', data: { '_token': $('input[name=_token]').val(), 'id': $("#fid").val(), 'name': $('#n').val() }, success: function(data) { $('.item' + data.id).replaceWith("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.name + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.name + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.name + "' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>"); } }); });
the controller logic when /editItem is called,
public function editItem(Request $req) { $data = Data::find ( $req->id ); $data->name = $req->name; $data->save (); return response ()->json ( $data ); }

Delete Operation using ajax :
Similar to edit operation. when the delete button is clicked with its respected row, a modal pops up, and the delete button in the modal deletes the item from the database and finally updating the view using jQuery.
When delete button is clicked, the following jQuery executes,
$(document).on('click', '.delete-modal', function() { $('#footer_action_button').text(" Delete"); $('#footer_action_button').removeClass('glyphicon-check'); $('#footer_action_button').addClass('glyphicon-trash'); $('.actionBtn').removeClass('btn-success'); $('.actionBtn').addClass('btn-danger'); $('.actionBtn').addClass('delete'); $('.modal-title').text('Delete'); $('.did').text($(this).data('id')); $('.deleteContent').show(); $('.form-horizontal').hide(); $('.dname').html($(this).data('name')); $('#myModal').modal('show'); });
When delete button in the modal is clicked,
$('.modal-footer').on('click', '.delete', function() { $.ajax({ type: 'post', url: '/deleteItem', data: { '_token': $('input[name=_token]').val(), 'id': $('.did').text() }, success: function(data) { $('.item' + $('.did').text()).remove(); } }); });
the controller logic for deletion,
public function deleteItem(Request $req) { Data::find ( $req->id )->delete (); return response ()->json (); }

Working Demo Project on Github
Code Explanation Video:
You can certainly see your skills in the work you write. The arena hopes for even more passionate writers like you who are not afraid to say how they believe. Always follow your heart.
Hi , Thanks for this simple and useful article ,it helped me a lot but i noticed there are two issues in this awesome article
1.you should delete or comment this line of code from deleteItem function dd ( $req->id );
2.fix html error from the topic end
Yea, Thanks for figuring the the issues.I overlooked them. Fixed now.
Cheers 🙂
Thanks a lot for clear and helpful info!
Cheers, keep browsing the site for more cool stuff and also feel free to subscribe to justlaravel.com so that you won’t miss any of the posts.
Keep Going !!
Sure niki 🙂
I still getting Error 500 even though there is _token . any solution? 🙂
If passing _token through data in ajax is a problem, then set up token in meta like this,
headers: { ‘X-CSRF-TOKEN’: $(‘meta[name=”_token”]’).attr(‘content’) }
id return ‘unidentified’. but after refresh, it shows the correct id. Any solution for that too. 🙂
Does it happen always or just once,
if it happens always, make sure you are getting the correct value for id here,
'id': $("#fid").val(),
and in the edit form you are setting this as
$('#fid').val($(this).data('id'));
and also check you are passing data object to button here,data-id="{{$item->id}}"
I mean when I try to insert data to table. ‘id’ show undefined when retrieving. but after refresh, the undefined replaced with ‘id’ value.
In the working demo posted here, http://justlaravel.com/demos/ajax-crud-operations-laravel/ i couldnt see any such issues. The same code is available at github here https://github.com/avinashn/Ajax-CRUD-example-in-laravel
You can compare the code to check if you are missing any minor issue.
Cheers,
Can you help me please, how can I use textarea instead of input text? when I change the input type=”text” to and I would like to add a data, it says that “The name field is required.”
You can change its input type from text and can replace with
The code has already some validations, follow this project at github https://github.com/avinashn/Ajax-CRUD-example-in-laravel
You can change the error message at /resources/views/welcome.blade.php
your syntax highlighter is terrible. can you change that theme and use prism syntax highlighter. other than this your website will look awesome
Yea will change it. The current syntax highlighter works well in desktop, looks messy when seen in mobile.
Hi,need help! curd operations not working.how to fix it?
Hello, all the CRUD operations are working fine here https://github.com/avinashn/Ajax-CRUD-example-in-laravel
Please compare your code to check what went wrong.
I download it from github and install it by as instruction given on github,but still not woking!
(update,add and delete) not working
Please add pagination section in this post, Thank You.
where is your modal code
Ah! I explained the modal code in parts,
Here is the modal code.
Also you can follow the code on this tutorial at github: https://github.com/avinashn/Ajax-CRUD-example-in-laravel
Thanks for the nice post, I have almost everthing working but whenever I edit a row the changes are not reflected on the table. Can you please take a look at the thread I posted on stackoverflow: https://stackoverflow.com/questions/44709620/jquery-not-replacing-table-row-after-edit Thanks!!
hello please i have question if i need to add more input and an image how i can do that
I tried to edit my crud but add, read and delete is working only the edit is not working.. I tried to trace it but still not working
$(document).on(‘click’, ‘.edit-modal’, function() {
$(‘#footer_action_button’).text(“Update”);
$(‘#footer_action_button’).addClass(‘glyphicon-check’);
$(‘#footer_action_button’).removeClass(‘glyphicon-trash’);
$(‘.actionBtn’).addClass(‘btn-success’);
$(‘.actionBtn’).removeClass(‘btn-danger’);
$(‘.actionBtn’).addClass(‘edit’);
$(‘.modal-title’).text(‘Edit’);
$(‘.deleteContent’).hide();
$(‘.form-horizontal’).show();
$(‘#fid’).val($(this).data(‘id’));
$(‘#cat_name’).val($(this).data(‘name’));
$(‘#points’).val($(this).data(‘points’));
$(‘#myModal’).modal(‘show’);
//console.log($(this).data(‘name’) + $(this).data(‘points’));
});
I added
$(‘#cat_name’).val($(this).data(‘name’));
$(‘#points’).val($(this).data(‘points’)); but it does not display in the modal.. can you help?
Are you sure you added `data-name` and `data-points` attributes to edit button and in modal you have elements with `cat_name` and `points` as id’s and also check for console for any errors.
Its same as adding name field, just add as many fields you want in the edit form
edit,delete buttons are not working
It is working fine in the demo here http://demos.justlaravel.com/ajax-crud-operations-laravel
Hi. Dear I download this app from github and I tryed to start but sooner this error message comes out PHP Fatal error: Class ‘app\Http\Controllers\Controller’ not found in C:\xampp\php\Ajax-CRUD-example-in-laravel\app\Http\Controllers\IndexController.php on line 11. I didn’t any modify so I wonder why it comes out. Could you teach me how to start this app please?
I tried and correct. But the result comes after i refresh the page, after I click update or delete there’s no errors and there is no changes, the result is coming when I refresh again. Why this is happen?