简体   繁体   English

Laravel 使用软删除数据进行唯一验证

[英]Laravel unique validation with softdeletes data

I want to use Laravel Unique validator with the implementation of softdeletes.我想使用 Laravel 唯一验证器来实现软删除。 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.这是我的代码示例。

在此处输入图像描述

 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');
}

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您需要先从数据库中删除约束,然后使用您的解决方案或这篇文章中的解决方案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)小心down()方法,如果表中有重复的 nim(软删除与否),您将无法恢复约束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM