Restore Soft Delete Laravel

0

I have the store method of a Size class, which uses the NewSizesRequest validator

public function store(NewSizesRequest $r) {
    if ($r->ajax()) {
        $this->sizesInterface->store($r->all());

        return response()->json("Mensaje");
    }
}

In the NewSizeRequest class I have the following rule:

  public function rules() {
        return [
            'size' => 'required|numeric|unique:sizes,size'
        ];
    }

The problem is in the following case:

I add an 'x' size to the database. Then I delete that record with SoftDelete. Now if I put to add a size again and repeat 'x' it tells me that it already exists even if it is not shown by the deleted_at.

I can not find a way to do that if it exists, make a $ size-> restore (), as if I had created it, but restore it just now!

    
asked by Juan Pablo B 27.09.2017 в 04:55
source

1 answer

2

For these cases, Laravel supports adding wheres additional to your validation of unique, you just have to add deleted_at,NULL at the end:

public function rules() {
    return [
        'size' => 'required|numeric|unique:sizes,size,NULL,id,deleted_at,NULL'
    ];
}

You can see the full documentation here

Then to restore or create your object you can use updateOrCreate on all records and then do restore

$this->sizesInterface->withTrashed()->updateOrCreate(
            ['size' => $r->input('size')],
            $r->all())->restore();

I have not been able to prove it, but that's the idea.

    
answered by 27.09.2017 / 06:50
source