Updating data asynchronously enhances the user experience in web applications. Laravel seamlessly integrates with AJAX, allowing you to update records without refreshing the page. In this blog post, we’ll explore how to change the status of a record using AJAX in Laravel, with examples using JavaScript, Bootstrap, and jQuery.
Setting Up the Laravel Backend
First, set up the necessary backend components in Laravel to handle the AJAX request for updating the status.
- Define the route in
routes/web.php
:
Route::post('/update-status', [StatusController::class, 'updateStatus'])->name('update.status');
- Create the
StatusController
and add theupdateStatus
method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class StatusController extends Controller
{
public function updateStatus(Request $request)
{
$post = Post::findOrFail($request->id);
$post->status = $request->status;
$post->save();
return response()->json(['success' => true]);
}
}
Creating the View
Next, create a view that displays the records and provides a button to toggle the status using AJAX.
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Post List</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>
<span class="badge {{ $post->status ? 'badge-success' : 'badge-danger' }}">
{{ $post->status ? 'Active' : 'Inactive' }}
</span>
</td>
<td>
<button class="btn btn-sm btn-primary toggle-status" data-id="{{ $post->id }}" data-status="{{ $post->status ? 0 : 1 }}">
Toggle Status
</button>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
@section('scripts')
<script>
$(document).ready(function () {
$('.toggle-status').on('click', function () {
var postId = $(this).data('id');
var newStatus = $(this).data('status');
var button = $(this);
$.ajax({
url: '{{ route("update.status") }}',
type: 'POST',
data: {
'_token': '{{ csrf_token() }}',
'id': postId,
'status': newStatus
},
success: function (response) {
if (response.success) {
button.data('status', newStatus ? 0 : 1);
button.siblings('.badge')
.removeClass('badge-success badge-danger')
.addClass(newStatus ? 'badge-success' : 'badge-danger')
.text(newStatus ? 'Active' : 'Inactive');
}
}
});
});
});
</script>
@endsection
Conclusion
Leveraging AJAX in Laravel allows you to create interactive web applications. By sending asynchronous requests to the server and updating the DOM accordingly, you provide a seamless user experience without page reloads.
Remember to adjust the code based on your specific requirements, such as the model structure, route naming, and additional validation or error handling.
With this approach, you can enhance your Laravel applications with AJAX functionality, making them more responsive and user-friendly.