I can provide you with an example of how to create an Ajax CRUD application in Laravel using jQuery and Bootstrap.
Assuming you have already created a Laravel application, you can follow these steps:
1. Install jQuery and Bootstrap through npm:
npm install jquery bootstrap
2. Add the following lines to your `resources/js/app.js` file:
window.$ = window.jQuery = require('jquery');
require('bootstrap');
3. Create a controller with CRUD functionality:
php artisan make:controller UserController --resource
This will generate a UserController with the basic CRUD methods.
4. Define the routes for the UserController in `routes/web.php`:
Route::resource('users', 'UserController');
5. Create a view for the index page with a table to display the users:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<a href="#" class="btn btn-primary btn-sm edit-user" data-id="{{ $user->id }}">Edit</a>
<a href="#" class="btn btn-danger btn-sm delete-user" data-id="{{ $user->id }}">Delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
@endsection
6. Create a view for the create and edit pages:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<form id="user-form">
@csrf
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
<div class="form-group">
<label for="password_confirmation">Confirm Password</label>
<input type="password" name="password_confirmation" id="password_confirmation" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
@endsection
7. Create a JavaScript file to handle the Ajax calls:
$(document).ready(function() {
// Load the index page
loadIndex();
// Handle the form submission
$('#user-form').submit(function(event) {
event.preventDefault();
var id = $('#id').val();
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
var password_confirmation = $('#password_confirmation').val();
var method = id ? 'PUT' : 'POST';
var url = id ? '/users/' + id : '/users';
$.ajax({
url: url,
method: method,
data: {
name: name,
email: email,
password: password,
password_confirmation: password_confirmation
},
success: function(response) {
$('#user-form')[0].reset();
$('#id').val('');
loadIndex();
}
});
});
// Handle the edit button click
$(document).on('click', '.edit-user', function() {
var id = $(this).data('id');
$.ajax({
url: '/users/' + id + '/edit',
method: 'GET',
success: function(response) {
$('#id').val(response.id);
$('#name').val(response.name);
$('#email').val(response.email);
$('#password').val('');
$('#password_confirmation').val('');
}
});
});
// Handle the delete button click
$(document).on('click', '.delete-user', function() {
var id = $(this).data('id');
if (confirm('Are you sure you want to delete this user?')) {
$.ajax({
url: '/users/' + id,
method: 'DELETE',
success: function(response) {
loadIndex();
}
});
}
});
// Load the index page via Ajax
function loadIndex() {
$.ajax({
url: '/users',
method: 'GET',
success: function(response) {
$('#content').html(response);
}
});
}
8. Update the `UserController` to handle the Ajax requests:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::all();
if (request()->ajax()) {
return view('users.index_ajax', compact('users'));
}
return view('users.index', compact('users'));
}
public function create()
{
return view('users.create');
}
public function store(Request $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'message' => 'User created successfully!'
]);
}
public function edit($id)
{
$user = User::findOrFail($id);
return response()->json($user);
}
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$user->name = $request->name;
$user->email = $request->email;
if ($request->password) {
$user->password = bcrypt($request->password);
}
$user->save();
return response()->json([
'message' => 'User updated successfully!'
]);
}
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return response()->json([
'message' => 'User deleted successfully!'
]);
}
}
9. Create a new view for the index page when it is loaded via Ajax:
@extends('layouts.app')
@section('content)
<table id="users-table" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>E-Mail</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<button type="button" class="btn btn-primary edit-user" data-id="{{ $user->id }}" data-name="{{ $user->name }}" data-email="{{ $user->email }}">Edit</button>
<button type="button" class="btn btn-danger delete-user" data-id="{{ $user->id }}">Delete</button>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="modal fade" id="user-modal" tabindex="-1" role="dialog" aria-labelledby="user-modal-label" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="user-modal-label">Create User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" action="{{ route('users.store') }}" id="user-form">
@csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autocomplete="email">
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Create') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
@section('scripts')
<script>
$(document).ready(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('users.index_ajax') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#create-user').click(function() {
$('#user-modal').modal('show');
$('#user-modal-label').text('Create User');
$('#user-form').attr('action', "{{ route('users.store') }}");
});
$('body').on('click', '.edit-user', function() {
var user_id = $(this).data('id');
var name = $(this).data('name');
var email = $(this).data('email');
$('#user-modal').modal('show');
$('#user-modal-label').text('Edit User');
$('#user-form').attr('action', "{{ route('users.update_ajax') }}");
$('#user-form').append('<input type="hidden" name="_method" value="PUT">');
$('#user-form').append('<input type="hidden" name="user_id" value="' + user_id + '">');
$('#name').val(name);
$('#email').val(email);
});
$('body').on('click', '.delete-user', function() {
var user_id = $(this).data('id');
if (confirm('Are you sure you want to delete this user?')) {
$.ajax({
url: "{{ route('users.destroy_ajax') }}",
method: "DELETE",
data: {
_token: "{{ csrf_token() }}",
user_id: user_id
},
success: function(response) {
$('#users-table').DataTable().ajax.reload();
},
error: function(response) {
console.log(response);
}
});
}
});
$('#user-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: "POST",
data: $(this).serialize(),
success: function(response) {
$('#user-form')[0].reset();
$('#user-modal').modal('hide');
$('#users-table').DataTable().ajax.reload();
},
error: function(response) {
console.log(response);
}
});
});
});
</script>
@endsection
10. Create a new route to handle the Ajax requests:
Route::get('/users', [UserController::class, 'index'])->name('users.index');
Route::get('/users/create', [UserController::class, 'create'])->name('users.create');
Route::post('/users', [UserController::class, 'store'])->name('users.store');
Route::get('/users/{id}/edit', [UserController::class, 'edit'])->name('users.edit');
Route::put('/users/{id}', [UserController::class, 'update'])->name('users.update');
Route::delete('/users/{id}', [UserController::class, 'destroy'])->name('users.destroy');
Route::get('/users-ajax', [UserController::class, 'index'])->name('users.index-ajax');
Subscribe to the Email Newsletter