WallyJ's avatar

Destroy route leads to Show route/view

This has got to be an easy fix but I can't see the tree for the forest. :)

I added a delete button to a list of contacts so each contact could be deleted. I Href'ed it to the contacts.destroy route, with an alert confirmation. When I click the button the confirmation window comes up. I click OK, and it shows me the contact view and does not delete the record. I am using resource routes for "contacts":

Controller @destroy:

public function destroy($id)
    {
        $contact = Contact::find($id);

        // Check for correct user
        if(auth()->user()->id !== $contact->user_id){
            return redirect('/contacts')->with('error', 'That Is Not Your Contact');
        }

        $contact->delete();
        return redirect('/contacts')->with('success', 'Contact Removed');
    }

Contacts View code for button:

<a class="btn btn-danger" onclick="return confirm('Are you sure you want to delete {{$contact->contact1firstname}} {{$contact->contact1lastname}}?')" href="{{route('contacts.destroy', $contact->id)}}">Delete</a>

Route as listed in the terminal:

|        | POST      | contacts                          | contacts.store        | App\Http\Controllers\ContactsController@store
               | web,auth     |
|        | GET|HEAD  | contacts                          | contacts.index        | App\Http\Controllers\ContactsController@index
               | web,auth     |
|        | GET|HEAD  | contacts/create                   | contacts.create       | App\Http\Controllers\ContactsController@create
               | web,auth     |
|        | DELETE    | contacts/{contact}                | contacts.destroy      | App\Http\Controllers\ContactsController@destroy
               | web,auth     |
|        | PUT|PATCH | contacts/{contact}                | contacts.update       | App\Http\Controllers\ContactsController@update
               | web,auth     |
|        | GET|HEAD  | contacts/{contact}                | contacts.show         | App\Http\Controllers\ContactsController@show

Why would it return my contacts.show view, showing the individual contact view?

0 likes
2 replies
bobbybouwmann's avatar
Level 88

A link cannot point to a destroy route. A destroy route only works with a POST request and specifying the method

<form action="{{route('contacts.destroy', $contact->id)}}" method="POST">
    @csrf
    @method('DELETE')

    <button type="submit">Delete</button>
</form>

There is another way to do a delete action as a GET request, but then you can't use the Route::delete option in your routes.

1 like
WallyJ's avatar

That makes sense as to why it showed the show route as it was a post request. Thanks!

Please or to participate in this conversation.