yassin
yassin

Reputation: 81

laravel 7 destroy route not working , it redirect me to the show route

when i try to delete a user it redirect me to the user profile ( show method) its not showing any errors , but it behaves like i asked for the show method

the route

Route::resource('/users', 'UsersController');

the link to the destroy method

 <a href="{{ route('users.destroy',$user->id) }}">delete</>

the destroy method in the controller

 public function destroy($id)
        {
            $user = User::find($id);
            $user->delete();
            return redirect('/users')->with('success','Utilisateur est supprimé');
        }

i tried excluding the destroy method from the ressource routes and creating it seperatly but it dont work

Upvotes: 1

Views: 1989

Answers (2)

Doro
Doro

Reputation: 357

Destroy method requires "delete" request method and cant be achieved with

<a href="{{ route('users.destroy',$user->id) }}">delete</a>

so use this instead

<form method="POST" action="{{ route('users.destroy',$user->id) }}">
    @csrf
    @method('delete')
    <button type="submit">delete</button> 
</form>

Upvotes: 0

porloscerros Ψ
porloscerros Ψ

Reputation: 5088

With the <a> tag you are sending a get request. So it could be used to get route like the show route:

<a href="{{ route('users.show',$user->id) }}">show</>

For delete, use a <form> instead, with a input named _method with value delete, and csrf field:

<form method="POST" action="{{ route('users.destroy',$user->id) }}">
    {{ csrf_field() }}
    {{ method_field('delete') }}
    <button type="submit">delete</button> 
</form>

You can read more on the docs:
Form Method Spoofing
Resource Controllers

Upvotes: 3

Related Questions