Laravel Deleting a Single Record


In Laravel, deleting data from the database using Eloquent allows you to remove records efficiently. You can delete data using various methods, depending on your needs—whether you want to delete a single record, multiple records, or perform soft deletes.

1. Deleting a Single Record

1.1. Finding and Deleting

To delete a specific record, first retrieve it using the model’s find() method or other querying methods. Then call the delete() method on the instance.

Example:

// Find the record by primary key $post = Post::find(1); if ($post) { // Delete the record $post->delete(); }

1.2. Using destroy() Method

The destroy() method allows you to delete a record by its primary key directly:

Example:

// Delete the record with ID of 1 Post::destroy(1);

You can also delete multiple records by passing an array of IDs:

Example:

// Delete records with IDs 1, 2, and 3 Post::destroy([1, 2, 3]);

2. Deleting Multiple Records

2.1. Using where() and delete()

To delete multiple records that match certain conditions, use the where() method combined with delete():

Example:

// Delete all posts with status 'draft' Post::where('status', 'draft')->delete();

This will remove all records from the posts table where the status column is draft.

3. Soft Deletes

Soft deletes allow you to keep records in the database but mark them as deleted. This is useful for scenarios where you want to restore deleted records or keep historical data.

3.1. Enabling Soft Deletes

To enable soft deletes, you need to add the SoftDeletes trait to your model and ensure your database table has a deleted_at column.

1. Add the SoftDeletes Trait:

use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; // ... }

2. Update Your Migration:

Add a deleted_at column to your table using a migration:

Schema::table('posts', function (Blueprint $table) { $table->softDeletes(); });

3.2. Soft Deleting Records

To soft delete a record, use the delete() method as usual:

Example:

$post = Post::find(1); if ($post) { $post->delete(); // This will set the deleted_at timestamp }

3.3. Restoring Soft Deleted Records

To restore a soft-deleted record, use the restore() method:

Example:

$post = Post::withTrashed()->find(1); if ($post) { $post->restore(); }

3.4. Querying Soft Deleted Records

  • Including Soft Deleted Records: Use withTrashed() to include soft-deleted records in your queries.

    Example:

    $posts = Post::withTrashed()->get();
  • Only Soft Deleted Records: Use onlyTrashed() to retrieve only the soft-deleted records.

    Example:

    $trashedPosts = Post::onlyTrashed()->get();

4. Force Deleting

To permanently delete a record from the database (bypassing soft deletes), use the forceDelete() method:

Example:

$post = Post::withTrashed()->find(1); if ($post) { $post->forceDelete(); // Permanently deletes the record }

5. Deleting Related Records

If your model has relationships with other models, you may need to delete related records as well.

5.1. Cascading Deletes

To automatically delete related records when a parent record is deleted, define cascading deletes in your model:

Example:

class Post extends Model { public function comments() { return $this->hasMany(Comment::class); } protected static function booted() { static::deleting(function ($post) { $post->comments()->delete(); // Delete related comments }); } }

This example uses the deleting event to ensure related comments are deleted when a post is deleted.

6. Using Query Builder

You can also perform deletions using Laravel’s query builder, especially when you need to work with raw SQL.

Example:

DB::table('posts')->where('status', 'draft')->delete();

This approach directly interacts with the database and bypasses Eloquent’s model features.


Summary

  • Single Record: Use find() to retrieve, and delete() to remove, or destroy() for direct deletion by ID.
  • Multiple Records: Use where() combined with delete() to remove records that match certain conditions.
  • Soft Deletes: Enable soft deletes with the SoftDeletes trait, use delete() to soft delete, restore() to recover, and forceDelete() for permanent removal.
  • Related Records: Handle related records using cascading deletes within the model.
  • Query Builder: Use DB::table() for direct SQL operations.

Laravel provides a range of methods to manage record deletions effectively, catering to different scenarios and needs.