Part II:

Hey there, this is part two of my previous lesson about Live Table CRUD in Laravel Using Ajax. In the previous lesson we have created the application structure and also we have seen how can we create/insert a data.

In today’s lesson we will see how to update and delete data.

Update

{{ csrf_field() }}
<div id="message"></div>
<table class="table table-bordered table-striped">
<tr> 												 
       <th>Name</th>
       <th>Author</th>
       <th>Description</th> 
       <th>Action</th> 
</tr>
<tr> 										                                  
       <td contenteditable="true" id="name"></td>
       <td contenteditable="true" id="author"></td>					       
       <td contenteditable="true" id="description"></td>									       
       <td><button class="btn btn-success" id="add"><i class="fa fa-plus-square"> 
       </i>Add</button></td>									</tr>
@foreach ($books as $book)										 
   <tr> 	
      <td>{{$book['name']}}</td>										 
      <td>{{$book['author']}}</td>
      <td>{{$book['description']}}</td>
     <td><a id="{{$book['id']}}" style="color:white" class="delete btn btn-danger"><i class="fa fa-trash-o"></i></a></td>
   </tr>    
@endforeach
</table> 

This is what we have from our last lesson. For today’s lesson we will modify the content in the foreach loop and we will add ajax code to listen for onblur event of the td tag.

Now change the content of the foreach loop

@foreach ($books as $book)										 
   <tr> 	
<td contenteditable="true" class="column_name" data-column_name="name"								data-id="{{$book['id']}}" data-desc="{{$book['description']}}" data-author="{{$book['author']}}">{{$book['name']}}</td> 										 
     <td contenteditable="true" class="column_author" data-column_name="author"		data-id="{{$book['id']}}" data-name="{{$book['name']}}"  data-desc="{{$book['description']}}" >{{$book['author']}}</td>
     <td contenteditable="true" class="column_description" data-column_name="description" data-id="{{$book['id']}}" data-name="{{$book['name']}}"  data-author="{{$book['author']}}">{{$book['description']}}</td> 
 <td><a id="{{$book['id']}}" style="color:white" class="delete btn btn-danger"><i class="fa fa-trash-o"></i></a></td>
   </tr>    
@endforeach

hhhmm, I think the code looks like little bit complex. let I explain it for you:

As we discussed in the previous lesson contenteditable=”true” is used to make the td tag editable. The others data-id,data-author,data-name,data-column_name are just a variable used to hold data under one td context. The event to edit the row will raise while onblur event occured. This means when we raise our cursor from the selected row. right after we edit the row and click outside of the row. every td has its own class name class="column_name" class="column_author"class="column_description". So, we have to handle onblur event for three of them.

Next will be adding the ajax function at the end of the index.blade.php. As a reminder first you need to have a jquery plugin. you should load jquery first before using the ajax method. Unless it will not work.

<script src="{{ asset('js/jquery.min.js') }}"></script> 
<script type="text/javascript">
jQuery(document).ready(function(){
var _token = $('input[name="_token"]').val();
//Name on blur
$(document).on('blur','.column_name',function(){
var column_name = $(this).data('column_name'); 
var column_value = $(this).text();
var id = $(this).data("id");
var author = $(this).data("author");
var description = $(this).data("desc");

if(column_value != ''){
	$.ajax({
		url:"{{ route('book.update_data') }}",
		method:"POST",
		data:{name:column_value,author:author,description:description,id:id,_token:_token},
		success:function(data)
		{
			$('#message').html(data);
		}
	});
}
});

//Description on blur
$(document).on('blur','.column_description',function(){
	var column_description = $(this).data('column_description'); 
	var column_value = $(this).text();
	var id = $(this).data("id");
	var author = $(this).data("author");
	var name = $(this).data("name");

	if(column_value != ''){
		$.ajax({
			url:"{{ route('book.update_data') }}",
			method:"POST",
			data:{name:name,author:author,description:column_value,id:id,_token:_token},
			success:function(data)
			{
				$('#message').html(data);
			}
		});
	}
});
//Author on blur
$(document).on('blur','.column_author',function(){
	var column_author = $(this).data('column_author'); 
	var column_value = $(this).text();
	var id = $(this).data("id");
	var name = $(this).data("name");
	var description = $(this).data("desc");

	if(column_value != ''){
		$.ajax({
			url:"{{ route('book.update_data') }}",
			method:"POST",
			data:{name:name,description:description,author:column_value,id:id,_token:_token},
			success:function(data)
			{
				$('#message').html(data);
			}
		});
	}
});
});	
</script>

Add the following code in web.php located in the /routes

Route::post('/book/update_data','BookController@update_data') -> name('book.update_data');

The last thing is to add update_data function in our controller.

public function update_data(Request $request)
    {  
        if($request -> ajax())
        { 
            $data = array(
                'name' => $request->name,
                'author' => $request->author,
                'description'=> $request->description
            );
            DB::table('books')->where('id',$request->id)->update($data);
            echo '<div class="alert alert-success">Data updated</div>'; 
        }
    }

Finally, we have finished setting up everything. Now, run it using

php artisan serve

Then click one cell you want and rewrite it as you want and click outside of the selected row. Your data will be updated.

Delete

Since we have seen how to create and how to update table deleting of table will be the simplest task. I have the following from my index.blade.php

 <td><a id="{{$book['id']}}" style="color:white" class="delete btn btn-danger"><i class="fa fa-trash-o"></i></a></td>

Whats left is only the jquery code and the controller function. Lets see them one by one.

The following is the jquery file that will be inserted inside index.blade.php

<script src="{{ asset('js/jquery.min.js') }}"></script> 
<script type="text/javascript">
jQuery(document).ready(function(){
var _token = $('input[name="_token"]').val();
$(document).on('click','.delete',function(){
	if(confirm("Are you sure you want to delete this record?")){
		var id = $(this).attr('id');
	// console.log(id);
		$.ajax({
			url: "{{ route('book.delete_data') }}",
			method:"POST",
			data:{id:id,_token:_token},
			success:function(data){
				$('#message').html(data);
				window.location.reload();
			}
		});
	}
    });
});	

Then I will add delete_data() function inside our controller.

public function delete_data(Request $request)
{
    if($request -> ajax())
    {
        DB::table('books')->where('id',$request->id)->delete();
        echo '<div class="alert alert-success">Book Deleted Successfully!</div>'; 
    }
}

Finally, modify your web.php file by adding the following:

Route::post('/book/delete_data','BookController@delete_data') -> name('book.delete_data');

That’s all!

Conclusion

In the above two part lessons we have learned that how can we create,, read, update and delete a record live on html table. Please feel free to ask any question. I’m always happy to hear from you. If you like the lesson share it for others.

Categories: LaravelPHPWeb

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *