Laravel unique validation with softdeletes data

Viewed 613

I want to use Laravel Unique validator with the implementation of softdeletes. I've been try many times but it produce an error like this. What should i do? Thanks in advance. Here's my code example.

enter image description here

 public function store(Request $request)
{
    $request->validate([
        'nama' => 'required',
        'nim' => [
            'required',
            'size:10',
            Rule::unique('students')->where(function ($query) {
                return $query->where('deleted_at', NULL);
            })
        ],
        'email' => 'required|email',
    ]);

    Student::create([
        'major_id' => $request->major_id,
        'nama' => $request->nama,
        'slug' => Str::of($request->nama)->slug('-'),
        'nim' => $request->nim,
        'email' => $request->email,
    ]);
    return redirect('/students')->with('status', 'Success');
}
1 Answers

The error you're getting is from a constraint in your database. Nothing you can do in the code can counter that. The database doesnt care for soft delete.

You need to remove the constraint from the database first, then use your solution or the one from this post check-if-name-is-unique-among-non-deleted-items-with-laravel-validation

To remove the constraint, run this query

ALTER TABLE students DROP CONSTRAINT students_nim_unique;

The best practice would be to create a new migration running this query. Carefull for the down() method, you will not be able to put back the constraint if there are dupplicate nim in the table (soft deleted or not)

Related