Laravel 12 - Delete Record User

Laravel 12 - Delete Record User

This feature allows admins to delete user records securely. It includes:

  • Confirmation prompt before deletion

  • Ajax support for smooth UI updates (optional)

  • Success message after deletion

  • CSRF protection and authorization checks

Step 1: Define the Route for User Deletion

The first step is to define the route that will handle the deletion of the user. We’ll create this route inside the routes/web.php file.

Route::group(['namespace' => 'App\Http\Controllers'], function () { Route::controller(DataListingController::class)->group(function () { Route::middleware('auth')->group(function () { // Define the delete route Route::post('delete-user', 'deleteRecord')->name('delete-user'); }); }); });

Explanation:

  • Route Grouping: We're grouping the route within the controller and applying the auth middleware to ensure that only authenticated users can access the route.

  • Route Method: We define a POST route because we are submitting data to delete the user.

Step 2: Controller Method to Handle User Deletion

Now, we'll create the method inside the DataListingController that will handle the deletion of the user and their associated avatar.

Here’s the deleteRecord method:

use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\File; use App\Models\User; public function deleteRecord(Request $request) { // Start the transaction to make it atomic DB::beginTransaction(); try { // Get the user ID and avatar from the request $userId = $request->user_id; $avatar = $request->avatar; // Find the user by ID, throw an exception if not found $user = User::where('user_id', $userId)->firstOrFail(); // Delete the user's avatar if it's not the default avatar if (!empty($avatar)) { $avatarPath = public_path('assets/images/' . $avatar); if (File::exists($avatarPath)) { File::delete($avatarPath); } } // Delete the user from the database $user->delete(); // Commit the transaction if everything is fine DB::commit(); // Redirect back with success message return redirect()->back()->with('success', 'User deleted successfully 🙂'); } catch (\Exception $e) { // Rollback the transaction if there is an error DB::rollBack(); // Log the error for debugging purposes Log::error('Error deleting user: ' . $e->getMessage()); // Redirect back with error message return redirect()->back()->with('error', 'User deletion failed 😞'); } }

Explanation:

  1. Transaction Handling: We use DB::beginTransaction() to start a database transaction. If anything fails, we can roll it back using DB::rollBack().

  2. Avatar Deletion: If the user has an avatar, we check if it exists in the public path and delete it using File::delete().

  3. Delete User: The delete() method removes the user from the database.

  4. Error Handling: If something goes wrong, an exception is caught, and we log the error while rolling back the transaction.

Step 3: Create the Modal for User Deletion

Now we need to create a modal that will ask the user for confirmation before deleting them.

Here's the modal HTML:

<!-- Modal for Delete User Confirmation --> <div class="modal fade" id="modalDeleteUser" tabindex="-1" aria-labelledby="modalDeleteUserLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <form action="{{ route('delete-user') }}" method="POST"> @csrf <div class="modal-header"> <h5 class="modal-title" id="modalDeleteUserLabel">Delete User</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body text-center"> Are you sure you want to delete the user <strong class="text-danger" id="d_name"></strong>? </div> <input type="hidden" id="d_user_id" name="user_id"> <input type="hidden" id="d_image-circle" name="avatar"> <div class="modal-footer justify-content-center"> <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-outline-danger" id="confirmDeleteUser">Delete</button> </div> </form> </div> </div> </div>

Explanation:

  • Modal Structure: This modal includes a title, body with a confirmation message, and two buttons: Cancel and Delete.

  • Hidden Inputs: We use hidden inputs to send the user_id and avatar to the server when the form is submitted.

  • Dynamic Data: The user’s name and avatar will be populated dynamically using JavaScript.

Step 4: JavaScript for Handling Modal Data

Now, let’s write the JavaScript that will populate the modal with user data when the delete button is clicked.

<script> $(document).on('click', '.userDelete', function() { const _this = $(this).closest('tr'); // Populate the modal with current user data $('#d_user_id').val(_this.find('.user_id').text()); $('#d_name').text(_this.find('.name').text()); $('#d_image-circle').val(_this.find('.image-circle').data('image-circle')); }); </script>

Explanation:

  • Event Listener: The script listens for a click on any element with the class .userDelete. This will be the delete button in your table.

  • Populate the Modal: When the delete button is clicked, the script finds the closest <tr> (table row), grabs the user ID, name, and avatar, and populates the modal with these values.

Step 5: Final Testing

  1. Check if the Delete Button Works: When you click the delete button next to a user, it should open the modal with the user's name and avatar.

  2. Confirm Deletion: Clicking the Delete button in the modal should send a POST request to the server, which deletes the user and their avatar (if applicable).

  3. Ensure Proper Redirection and Messages: After deletion, you should see a success or error message on the page.

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close