In this blog post, we’ll explore how to create a one-page CRUD (Create, Read, Update, Delete) application using Laravel, jQuery, and DataTables. This approach can be applied to various types of data management systems, providing a smooth and efficient user experience.
Key Features
Server-side processing with DataTables
AJAX-powered form submissions
Modal-based create and edit forms
Inline editing and deleting of records
Responsive design using Bootstrap
The View (Blade Template)
Our view combines the list of records with the form for creating/editing entries, all on one page. Here are the key elements:
DataTable
We use a DataTable to display the list of records:
<table class="table table-bordered table-striped" id="data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Created At</th>
<th>Actions</th>
</tr>
</thead>
</table>
Modal Form
We use a Bootstrap modal for the create/edit form:
div class="modal fade" id="crud-modal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="crud-form">
@csrf
<input type="hidden" name="id" id="item-id">
<!-- Add your form fields here -->
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
The Controller
Our controller handles all CRUD operations. Here’s a basic structure:
class CrudController extends Controller
{
public function index()
{
if (request()->ajax()) {
$items = YourModel::select('*');
return DataTables::of($items)
->addIndexColumn()
->addColumn('actions', function ($row) {
$actionBtn = '<button class="edit-btn btn btn-success btn-sm" data-id="'.$row->id.'">Edit</button> ';
$actionBtn .= '<button class="delete-btn btn btn-danger btn-sm" data-id="'.$row->id.'">Delete</button>';
return $actionBtn;
})
->rawColumns(['actions'])
->make(true);
}
return view('your-view');
}
public function store(Request $request)
{
// Validation and creation logic
}
public function edit($id)
{
$item = YourModel::findOrFail($id);
return response()->json($item);
}
public function update(Request $request, $id)
{
// Validation and update logic
}
public function destroy($id)
{
$item = YourModel::findOrFail($id);
$item->delete();
return response()->json(['message' => 'Item deleted successfully.']);
}
}
JavaScript/jQuery
The JavaScript code handles the client-side interactions:
$(document).ready(function() {
// Initialize DataTable
var table = $("#data-table").DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('items.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'description', name: 'description'},
{data: 'created_at', name: 'created_at'},
{data: 'actions', name: 'actions', orderable: false, searchable: false},
]
});
// Form Submission
$('#crud-form').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
var url = $('#item-id').val() ?
"{{ route('items.update', ':id') }}".replace(':id', $('#item-id').val()) :
"{{ route('items.store') }}";
var method = $('#item-id').val() ? "PUT" : "POST";
$.ajax({
url: url,
type: method,
data: formData,
success: function(response) {
$('#crud-modal').modal('hide');
table.ajax.reload();
toastr.success(response.message);
},
error: function(xhr) {
var errors = xhr.responseJSON.errors;
// Display errors to user
}
});
});
// Edit Item
$(document).on('click', '.edit-btn', function() {
var id = $(this).data('id');
$.get("{{ route('items.edit', ':id') }}".replace(':id', id), function(data) {
$('#crud-modal').modal('show');
$('#item-id').val(data.id);
// Populate form fields with data
});
});
// Delete Item
$(document).on('click', '.delete-btn', function() {
var id = $(this).data('id');
if(confirm("Are you sure you want to delete this item?")) {
$.ajax({
url: "{{ route('items.destroy', ':id') }}".replace(':id', id),
type: 'DELETE',
data: {
"_token": "{{ csrf_token() }}"
},
success: function(response) {
table.ajax.reload();
toastr.success(response.message);
}
});
}
});
});
Key Takeaways
Single Page Application: By using AJAX and modals, we’ve created a seamless single-page experience for users.
Real-time Updates: The DataTable is refreshed after each operation, ensuring users always see the most up-to-date data.
Reusable Structure: This approach can be easily adapted for various types of data in your application.
Enhanced User Experience: The use of DataTables for pagination and sorting, along with toastr for notifications, improves the overall user experience.
Scalability: As your application grows, this structure can be maintained and expanded upon.
Conclusion
Building a one-page CRUD application using Laravel and jQuery offers a smooth and efficient user experience. By leveraging AJAX for all operations, we minimize page reloads and create a more responsive application. This approach serves as a solid foundation for building more complex administrative interfaces or data management systems.
Remember to always implement proper security measures, such as CSRF protection, input validation, and user authentication, when building CRUD applications.
Top comments (0)