Unique Validation with Soft Delete in Laravel 10

In Laravel, you can perform unique validations on fields while considering soft deletes. Soft deletes allow you to mark records as “deleted” without actually removing them from the database. Here’s an example that demonstrates how to implement unique validation with soft delete functionality in Laravel.

Many times we need to create a unique validation with soft deleted functionality eg. email, username, post slug, etc. In this tutorial, you will find the best examples of unique validation with solf delete in laravel using store and update the form.

Using Store Method

Here’s an example of how you can define the validation rules in a Laravel controller when store the data:

public function store(Request $request)
{
    $request->validate([
        'email' => 'required|unique:users,email,NULL,id,deleted_at,NULL'
    ]);
}

Using Update Method

When your user is deleted and you want to update existing records to using the deleted email then you can use the unique validation on updating the record:

public function update(Request $request, $id)
{
    $request->validate([
        'email' => 'required|unique:users,email,'.$id.',id,deleted_at,NULL',
    ]);
}

Using Rule Method

Here’s an example of how you can define the validation rules in a Laravel controller:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'username' => [
                'required',
                Rule::unique('users')->where(function ($query) {
                    $query->whereNull('deleted_at');
                }),
            ],
            // Other validation rules...
        ]);

        // Process the request if validation passes
    }
}

In this example, we use the Rule::unique validation rule along with the where clause to check for uniqueness among non-deleted records. The 'users' argument passed to unique specifies the table name to perform the uniqueness check on.

The where callback in the whereNull('deleted_at') closure filters the records by checking if the deleted_at column is null, which indicates that the record has not been deleted.

By using this approach, the validation rule will consider only the non-deleted records when checking for uniqueness.

That’s it! You can now perform unique validations while considering soft deletes in Laravel by the above examples.

Leave a Comment