Alex Lomia
Alex Lomia

Reputation: 7235

Action refuses to return the boolean value

I have the standard destroy action:

public function destroy($id)
{
    return Quiz::find($id)->delete();
}

Which is accessed by the following AJAX call:

// The CSRF token is included automatically!
$.ajax({
    url: /quiz/10,
    type: 'POST',
    data: {_method: 'DELETE'},
    success: function(response){
        if(response){
            // do stuff..
        }
    }
});

The problem

When the AJAX call is made, chrome console shows the following error:

enter image description here

Strange thing is, that everything works if I remove the return, but I need the status code to be returned. Can somebody explain why is this happening? Or, at least, how to debug this problem?

Update

Everything starts working properly if I rewrite the destroy action like this:

public function destroy($id)
{
    return Quiz::delete($id);
}

But I still can't understand why doesn't the first action work?

Upvotes: 1

Views: 114

Answers (3)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

you can't return a Boolean value (Quiz::find($id)->delete(); returns true or false), It's better to do something like below,

$deleted =  Quiz::find($id)->delete(); //this will return true/false

return response()->json(['success' => $deleted]);

In the frontend

$.ajax({
    url: /quiz/10,
    type: 'POST',
    data: {_method: 'DELETE'},
    success: function(response){
        if(response.success == true){
            // do stuff..
        } else {
            // something went wrong when deleting the record.
        }
    }
});

Upvotes: 1

huuuk
huuuk

Reputation: 4795

Seems Trying to get property of non-object error occurs.
Try this

public function destroy($id)
{
    return Quiz::destroy($id);
}

Upvotes: 1

Achraf Khouadja
Achraf Khouadja

Reputation: 6279

You can do something like this

public function destroy($id) {

    $quiz =  Quiz::find($id);
    $quiz->delete();

    if ($quiz) {
        return response()->json('true');
    } else {
        return response()->json('false');
    }
}

the response is oviously a json that contains true if the quiz has been deleted or false in case of error

im not good at js but :

$.ajax({
    url: /quiz/10,
    type: 'POST',
    data: {_method: 'DELETE'},
    success: function(response){
        if(response == 'true'){ // should work i guess
            // do stuff..
        }
    }
});

Upvotes: 0

Related Questions