Home » Intermediate » 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.
Working Demo:
Here we will go through a simple example to cover all the CRUD operations.
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,
ADD
ADD |
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(”
“); } }, }); $(‘#name’).val(”); }); “);
$(“#add”).click(function() { ‘_token’: $(‘input[name=_token]’).val(), ‘name’: $(‘input[name=name]’).val() success: function(data) { $(‘.error’).removeClass(‘hidden’); $(‘.error’).text(data.errors.name); $(‘#table’).append(“ | ||
” + data.id + “ | ” + data.name + “ | Edit Delete |
the route for /addItem
,
Route::post ( ‘/addItem’, ‘IndexController@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 ); } }
public function addItem(Request $request) { $validator = Validator::make ( Input::all (), $rules ); if ($validator->fails ()) return Response::json ( array ( ‘errors’ => $validator->getMessageBag ()->toArray () $data->name = $request->name; 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’ );
Route::get ( ‘/’, ‘IndexController@readItems’ ); |
The controller logic for readItems function,
public function readItems(Request $req) { $data = Data::all (); return view ( ‘welcome’ )->withData ( $data ); }
public function readItems(Request $req) { return view ( ‘welcome’ )->withData ( $data ); |
The view for displaying data,
@foreach($data as $item) @endforeach
# | Name | Actions |
---|---|---|
{{$item->id}} | {{$item->name}} | Edit Delete |
“); } }); });
ajax CRUD operations in laravel – justlaravel.com 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, $(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 is clicked the logic for updation 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(“ |
|||||||
” + data.id + “ | ” + data.name + “ | Edit Delete |
“);
$(‘.modal-footer’).on(‘click’, ‘.edit’, function() { ‘_token’: $(‘input[name=_token]’).val(), success: function(data) { $(‘.item’ + data.id).replaceWith(“ | ||
” + data.id + “ | ” + data.name + “ | Edit Delete |
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 ); }
public function editItem(Request $req) { $data = Data::find ( $req->id ); $data->name = $req->name; return response ()->json ( $data ); |
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,
$(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’); });
$(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(); } }); });
$(‘.modal-footer’).on(‘click’, ‘.delete’, function() { ‘_token’: $(‘input[name=_token]’).val(), 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 (); }
public function deleteItem(Request $req) { Data::find ( $req->id )->delete (); return response ()->json (); |