1

I created a web route that must delete a contact based on a specific id and it looks like this:

Route::delete('/api/deleteContact/{id}', 'ContactController@destroy');

Then inside the controller, I have the following:

public function destroy($id)
{
    // delete a contact by id
    return response()->json(Contact::whereId($id), 200);
}

Inside one of my blade template files, I call the Vue component which displays the list of contacts:

<table class="table">
    <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Phone</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="contact in contacts">
            <td> {{ contact.id }} </td>
            <td> {{ contact.name }} </td>
            <td> {{ contact.phone }} </td>
            <td><button class="btn btn-secondary">Edit</button></td>
            <td><button @click="deleteContact(contact.id)" class="btn btn-danger">Delete</button></td>
        </tr>
    </tbody>
</table>

The delete button calls the deleteContact method and received the contact id in question.

The method looks like this:

deleteContact(id){
    axios.delete('/api/deleteContact/' + id)
    .then(res => {
        for(var i = 0; i < this.contacts.length; i++) {
            if(this.contacts[i].id == id) {
                this.contacts.splice(i, 1);
            }
        }
    })
    .catch(err => console.log(err));
}

When I click to delete, the promise(then) occurs, however, after refreshing the page, I noticed that nothing was deleted and I see no errors in the console.

How can I successfully delete the contact based on the id passed in the deleteContact function ?

2
  • 2
    Contact::whereId($id) this will not delete, you have to add ->delete() at the end Commented Jul 26, 2019 at 18:33
  • I cannot believe that I failed to noticed that. Appreciate the support Commented Jul 26, 2019 at 18:36

1 Answer 1

3

You have to append delete at the end of query like this:

public function destroy($id)
{
    // delete a contact by id
    return response()->json(Contact::where('id',$id)->delete(), 200);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.