Problem with Validate Rules Laravel

0

I have a Table Role with the attributes id and Role .

I do some of the roles softdelete .

Now, when I want to create a new role I have the following rules:

public function rules() {
  return [
    'role' => 'required|unique:role,role|alpha'
  ];
}

If the role does not exist, it will create it.

public function store(NewRoleRequest $request) {        
  $request['role'] = strtoupper($request->input('role'));
  $this->roleRepo->create($request->all());
  return redirect()
    ->route('role.create')
    ->with('create-success', 'Role agregado correctamente.');      
}

What I can not do is that if the Role already exists in the database but it has softDelete , it will restore it. That is, when you go to the method store and check the rules, see some form if that role is already that I want to create as sofdelete , if it is the restore() , but believe it.

Also if the attribute is unique, it automatically redirects me to the view again.

    
asked by Juan Pablo B 26.10.2016 в 14:54
source

2 answers

0

There are several ways to solve it, one is to consult the model before validation, to see if the role exists in the "trashed", restore it and not validate unique. Otherwise, validate unique.

The solution would be something like that (it's not proven, it's to guide you):

public function rules()
{
    $trashedRole = Role::onlyTrashed()
                       ->where('role', $this->input('role'))
                       ->first();

    // si no está en los elementos borrados, validamos unique
    if ($trashedRole->isEmpty()) {
        return [
            'role' => 'required|unique:role,role|alpha'
        ];
    }

    // restauramos y no validamos unique
    $trashedRole->restore();
    return [
        'role' => 'required|alpha'
    ]; 
}
    
answered by 26.10.2016 в 15:50
0

Observing a few other answers, I think it's a software architecture problem. The purpose of softdelete is the possibility of leaving a record inactive to later restore it in the future.

So, if you will use softdelete and you need it to be unique, you should only use it in restoring and updating.

Source:

How to use a unique validation rule / unique columns with soft deletes?

Laravel Soft Delete Unique column name

    
answered by 26.10.2016 в 17:07