Laravel Soft Delete Unique column name

Alankar More picture Alankar More · Oct 17, 2014 · Viewed 9k times · Source

Suppose I have category table and I have used soft delete on it. Now first time I have added one category "Test" after that I have delete this category so it will update my deleted_at column from the database.

Now when again I am trying to add category with name "Test" it is saying me that this name has been taken. I have tried with rules which are posted Here.

But it is not working. I have used trait in my model. Below is my model code.

<?php
namespace App\Models;

use Illuminate\Support\Facades\Validator as Validator;
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Category extends \Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

    /**
     * Guarded fields which are not mass fillable
     *
     * @var array
     */
    protected $guarded = array('id');

    /**
     * Name of the table used
     *
     * @var string
     */
    protected $table = 'travel_categories';

    /**
     * Validating input.
     *
     * @param array $input
     * @return mixed (boolean | array)
     */
    public static function validate($input, $id = null) {
        $rules = array(
            'name' => array('required','min:2','max:100','regex:/[a-zA-z ]/','unique:travel_categories,name,NULL,id,deleted_at,NULL'),
            'description' => 'Required|Min:2',
            'image' => 'image'
        );
        if ($id) {
            $rules['name'] = 'Required|Between:3,64|Unique:travel_categories,name,'.$id;
        }

        $validation = Validator::make($input,$rules);

        return ($validation->passes())?true : $validation->messages();
    }
}

Answer

Seiji Manoan picture Seiji Manoan · Oct 17, 2014

Did you understand the soft deleting purpose? It will only flag the data to be inactive. It will be there though.

So, if you define the values of that column must be unique, it is right you could not create other one alike.

  • If it needs to be unique, so you should restore and update the data.
  • If it can have many ones, so you should remove the unique key applied on it (and call it by relationship for instance).

Look at: Laravel Eloquent Soft Deleting