Deleting Records with Conditions in Laravel Query Builder

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, as a powerful PHP framework, offers an elegant query builder to manipulate your database with an expressive syntax. In this post, we’ll explore how to delete records with conditions using Laravel’s Query Builder. Deleting records correctly is important, as it impacts data integrity and application flow. We’ll explore everything from basic to advanced deletions with multiple examples and expected outcomes.

Before proceeding, you should have a basic understanding of Laravel, Eloquent ORM, and Composer. You should also have Laravel installed on your system with a configured database connection.

Basic Deletions in Query Builder

To start with the basics, let’s consider you want to delete a record from your ‘users’ table based on a specific condition, such as when the user’s id is ‘1’. Here’s how you would do it:

$deletedRows = DB::table('users')->where('id', 1)->delete();

This command instructs Laravel to delete the record where the id equals ‘1’. The delete() method executes the operation and returns the number of affected rows.

Using Multiple Conditions

Sometimes you may need to apply multiple conditions when deleting records. The following example demonstrates how to delete users that are ‘inactive’ and have a ‘subscription_end_date’ that is in the past:

$deletedRows = DB::table('users')
    ->where('status', 'inactive')
    ->whereDate('subscription_end_date', '<', now())
    ->delete();

In this case, Query Builder chains condition methods before calling delete(), showing how fluent and readable Laravel’s syntax is.

Deleting Records Using Subqueries

Now let’s look at a more complex scenario where you need to perform deletion based on a subquery. For example, you want to delete all posts that have no comments. First, you would create a subquery to select all post ids that have comments and then delete the posts that are not in this subselection:

$postsWithComments = DB::table('comments')
    ->select('post_id')
    ->distinct();

$deletedRows = DB::table('posts')
    ->whereNotIn('id', $postsWithComments)
    ->delete();

This approach utilizes a subquery to articulate an ‘exclusion’ condition in a deletion operation.

Soft Deleting

Laravel also provides a mechanism for ‘soft deleting’ records. When you soft delete a record, it’s not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To perform a soft delete, your model must use the SoftDeletes trait:

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

$user = User::find(1);
$user->delete();

This snippet illustrates a ‘soft delete’ operation. The ‘users’ record with id ‘1’ won’t be physically removed but will have its deleted_at column updated.

Advanced Conditionals: Deleting with Joins

Query Builder supports more advanced scenarios like deletions with joins. Suppose you need to delete posts from the ‘posts’ table that have been tagged as ‘deprecated’ in the ‘tags’ table. You could achieve this with the following code:

$deletedRows = DB::table('posts')
    ->join('post_tags', 'posts.id', '=', 'post_tags.post_id')
    ->join('tags', 'post_tags.tag_id', '=', 'tags.id')
    ->where('tags.name', 'deprecated')
    ->delete('posts.*');

Note that we specify delete('posts.*') to clarify we are deleting data from the ‘posts’ table.

Keeping Things Secure

When using the Query Builder to delete records, it’s crucial to safeguard against SQL injection attacks. Laravel’s Query Builder automatically prepares your queries and escapes variables. However, you should always validate and sanitize user input before applying it to a query.

Conclusion

Throughout this guide, we have explored various methods to delete records with conditions using Laravel’s Query Builder. From the simple direct conditional deletion to the more advanced soft deleting and deletions with joins, Laravel offers secure and streamlined ways to handle data manipulation. With this knowledge, you can confidently manage your database records using this powerful feature of Laravel.