📅  最后修改于: 2023-12-03 15:32:35.832000             🧑  作者: Mango
本示例展示了如何在 Laravel 中使用模态对话框来编辑表单。我们将使用 jQuery 和 Bootstrap 框架,以及 Laravel 的表单请求功能来处理数据。
Route::put('/user/{id}', 'UserController@update')->name('user.update');
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
]);
$user->update($validatedData);
return response()->json(['success'=>'User updated successfully']);
}
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editModalLabel">Edit User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" action="" id="editForm">
@csrf
@method('PUT')
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" aria-describedby="emailHelp" value="">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
$(document).ready(function() {
$('#editUser').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var name = button.data('name') // Extract info from data-* attributes
var email = button.data('email')
var actionUrl = button.data('route')
var modal = $(this)
modal.find('.modal-body #name').val(name)
modal.find('.modal-body #email').val(email)
modal.find('.modal-body #editForm').attr('action', actionUrl)
})
$('#editForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: e.target.action,
data: $('#editForm').serialize(),
success: function(response) {
$('#editModal').modal('hide')
alert(response.success)
},
error: function(response) {
console.log(response)
alert('Error updating user.')
}
});
});
});
本示例演示了如何使用 Laravel 构建简单但功能强大的模态编辑对话框。我们使用了 Laravel 的表单请求验证功能,以确保我们的数据是安全的。这一示例只是展示了 Laravel 的众多功能之一,我们可以在开发过程中使用 Laravel 进行更高级的操作。