Laravel 4 - how to use a unique validation rule / unique columns with soft deletes?

前端 未结 5 1243
盖世英雄少女心
盖世英雄少女心 2020-12-29 11:24

Assume, you are trying to create a new user, with a User model ( using soft deletes ) having a unique rule for it\'s email address, but there exists a trashed user within th

相关标签:
5条回答
  • 2020-12-29 11:57

    You can validate passing extra conditions:

    'unique:users,deleted_at,NULL'
    
    0 讨论(0)
  • 2020-12-29 11:58

    This sounds like an issue with your business logic rather than a technical problem.

    The purpose of a soft delete is to allow for the possibility that the soft-deleted record may be restored in the future. However, if your application needs uniqueness of email (which is completely normal), you wouldn't want to both create a new user with that email address and be able to restore the old one as this would contravene the uniqueness requirement.

    So if there is a soft deleted record with the email address for which you are adding as a new record, you should consider instead restoring the original record and applying the new information to it as an update, rather than trying to circumvent the uniqueness check to create a new record.

    0 讨论(0)
  • This is the best approach

            'email' => 'required|email|unique:users,email,NULL,id,deleted_at,NULL',
    

    It give you this query

    select count(*) as aggregate from `users` where `email` = ? and `deleted_at` is null
    
    0 讨论(0)
  • 2020-12-29 12:12

    Your Eloquent model should have the $softDeletes property set. If so, then when you perform a WHERE check, like User::where('username', 'jimbob'), Eloquent will automatically add in the query WHERE deleted_at IS NULL... which excludes soft deleted items.

    0 讨论(0)
  • 2020-12-29 12:20

    Laravel offers "Additional Where Clauses".

    My url validation rule (from the update model method) looks like this:

    $rules['url'] = 'required|unique:pages,url,'.$page->id.',id,deleted_at,NULL';
    

    This means that the url must be unique, must ignore the current page and ignore the pages where deleted_at id not NULL.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题