How to delete data from database using Laravel 7 framework

How to delete data from database using Laravel 7 framework

How to Delete Data from Database using Laravel 7 Framework

In Laravel, deleting data from the database can be done easily using Eloquent ORM or the query builder. Below is a guide on how to delete a record using both methods in Laravel 7.

1. Setup Routes

First, define the routes to handle the delete functionality in your routes/web.php:

use App\Http\Controllers\RecordController; Route::get('/record/{id}/delete', [RecordController::class, 'destroy'])->name('record.delete');
  • The route listens for a GET request to /record/{id}/delete and calls the destroy method in the RecordController.

2. Create Controller Method for Deleting Data

You will need to create a controller method to handle the deletion of a record. If you don't already have a controller, you can generate one:

php artisan make:controller RecordController

Then, in the app/Http/Controllers/RecordController.php, add the following code to handle the delete operation.

namespace App\Http\Controllers; use App\Record; use Illuminate\Http\Request; class RecordController extends Controller { // Other methods... // Method to delete the record public function destroy($id) { // Find the record by ID $record = Record::findOrFail($id); // Delete the record $record->delete(); // Redirect with a success message return redirect()->route('record.index')->with('success', 'Record deleted successfully!'); } }

Explanation:

  • findOrFail($id): This method is used to find the record by its ID. If the record does not exist, it will automatically throw a 404 error.

  • $record->delete(): This method deletes the record from the database.

  • After deletion, the user is redirected to the record.index route (where you can list all records) with a success message.

3. Create Blade View with Delete Link

Now, create or modify the Blade view where you list the records and provide a link to delete each record. For example, you might have a resources/views/records/index.blade.php:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Records List</title> </head> <body> <h1>Records</h1> @if(session('success')) <p style="color: green;">{{ session('success') }}</p> @endif <table border="1"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody> @foreach($records as $record) <tr> <td>{{ $record->name }}</td> <td>{{ $record->email }}</td> <td> <!-- Delete Link --> <a href="{{ route('record.delete', $record->id) }}" onclick="return confirm('Are you sure you want to delete this record?')">Delete</a> </td> </tr> @endforeach </tbody> </table> </body> </html>

Explanation:

  • The Delete link triggers a GET request to /record/{id}/delete, which will invoke the destroy method in the controller.

  • JavaScript confirm method: Before proceeding with the deletion, a confirmation dialog is displayed to the user.

4. List Records in the Controller

In your RecordController,You will also need a method to list all the records so that you can display them in the Blade view.

public function index() { // Retrieve all records from the database $records = Record::all(); // Return the view with the records return view('records.index', compact('records')); }

5. Define the Route for Listing Records

Don't forget to define a route for listing the records in your routes/web.php:

Route::get('/records', [RecordController::class, 'index'])->name('record.index');

6. Optional: Soft Delete (Optional)

If you don't want to completely remove the data from the database but rather "soft delete" it (mark it as deleted), you can use Laravel's SoftDeletes feature. This way, records will be marked as deleted without actually removing them from the database.

First, make sure your Record model uses the SoftDeletes trait:

namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Record extends Model { use SoftDeletes; // Other model code... }

Then, add a deleted_at Column to the table by creating a migration:

php artisan make:migration add_deleted_at_to_records_table --table=records

Modify the migration to add the deleted_at column:

public function up() { Schema::table('records', function (Blueprint $table) { $table->softDeletes(); // This adds the deleted_at column }); }

Run the migration:

php artisan migrate

Now, in your RecordController, You can modify the destroy method to perform a soft delete instead of a hard delete:

public function destroy($id) { // Find the record by ID $record = Record::findOrFail($id); // Soft delete the record $record->delete(); // Redirect with a success message return redirect()->route('record.index')->with('success', 'Record deleted successfully!'); }

With soft deletes, records are not permanently removed from the database. They are marked with a timestamp in the deleted_at column. You can still query them, but they won't show up in normal queries unless you include withTrashed().

7. Test the Delete Functionality

  1. Go to the records list page (/records).

  2. Click the Delete link next to any record.

  3. Confirm the deletion in the prompt.

  4. The record will be deleted from the database, and you will be redirected back to the records list page with a success message.

Conclusion

  • Delete Data: You learned how to delete data using the delete() method in Laravel.

  • Soft Delete (Optional): You can choose to soft delete records if you don't want to permanently remove them from the database.

  • Confirm Delete: Added a JavaScript confirmation dialog before deleting records.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close