Friday, March 10, 2017

Restoring soft-deleted entities sets an invalid timestamp in the deleted_at column

I am trying to restore a soft-deleted entity in Laravel 4.2 however it keeps setting the timestamp of deleted_at column to an invalid format.

Instead of setting it to NULL it sets it to 0000-00-00 00:00:00 and it preventes me to actually restore the soft-deleted entity since Laravel keeps recognizing it as deleted because the column is not empty.

I tried with and without a setter to the deleted_at attribute as well but it does not work.

The code is actually very simple: I submit a PUT request to nullify the deleted_at column so that the user gets restored, but unsuccessfully.

// Javascript
$("#enable-user").on('click', function (event) {
    var action = $(this).attr('action');

    swal({
        title: "Are you sure?",
        text: "Do you want to reactivate this user?",
        type: "warning",
        showCancelButton: true,
        html: true,
        cancelButtonText: "Cancel",
        confirmButtonText: "Continue",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
    },
    function(isConfirm) {
        if (isConfirm) {
            $.ajax({
                type: 'PUT',
                url: action,
                headers: {
                    'X-CSRF-Token': $("input[name='_token']").attr('value')
                },
                data: {
                    deleted_at: null
                },
                success: function(data) {
                    sweetAlert("Sii!", "User re-activated successfully!", "success");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status === 401) {
                        sweetAlert("Oops...", jqXHR.responseJSON.message, "error");
                    } else {
                        sweetAlert("Oops...", "Something went wrong!", "error");
                    }
                }
            });
        }
    });
});

// UsersController
public function updateUser($userId)
{
    $input = Input::all();
    $user  = User::withTrashed()->where('id', '=', $userId)->firstOrFail();

    if (array_key_exists('exports', $input)) {
        $user->exportAccounts()->sync([]);
        $user->exportAccounts()->sync($input['exports']);
        unset($input['exports']);
    }

    if (array_key_exists('regions', $input)) {
        $user->regions()->sync([]);
        $user->regions()->sync($input['regions']);
        unset($input['regions']);
    }

    $user->update($input);

    $user->queueUpdateToAlgolia();

    return Response::json([], 200);
}

This is what appears in the database after restoring:

database



via GiamPy

Advertisement