The route: Route::post
should be:
Route::delete
i.e. use the Route::delete method to initiate a delete request.
Hello guys im having a bit of a trouble understanding the @method function, especially when deleting records, heres my form request:
<form method="POST" action="/posts/{{$post->slug}}">
@csrf
@method('DELETE')
<button> <span> <i class="fas fa-skull-crossbones"></i> Delete </span> </button>
</form>
The part below is the confusing part for me, I know that when specifying a route for a controllers function, one should specify a method that the Route will follow, then use a path that will return a view, we can pass in a wildcard that needs to be included in the function as the parameter, then the controllers name with the function.
If i look and compare both files, everything looks "okay", I got the variable im using in my function $post as well as the parameter. Ive read that theres a convention to follow when specifying the "destroy" method on our Routes, which is like the one below.
At first I thought it could be "/posts/{$slug}/destroy" but maybe you could tell me more about that if you wish.
Route::post('/posts/destroy/{slug}', 'PostsController@destroy')->middleware('auth');
At the PostsController.php file my function looks like this:
public function destroy(Post $post, $slug)
{
$post = Post::findOrFail($slug);
$post->delete();
return redirect('posts/');
}
Since all of functions finding had been done using the slug of the post, I am also passing it inside its parameters and im redirecting (for now) to the page where ALL the posts are shown.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The DELETE method is not supported for this route. Supported methods: GET, HEAD, PUT.
Why do you use slug?
With id it will be
Route::delete('/posts/destroy/{id}', 'PostsController@destroy')->middleware('auth');
public function destroy($id)
{
$post = Post::findOrFail($id);
$post->delete();
return redirect('posts/');
}
<form method="POST" action="/posts/destroy/{{ $post->id}}">
@csrf
@method('DELETE')
<button type="submit">
<span>
<i class="fas fa-skull-crossbones"></i> Delete
</span>
</button>
</form>
Or you can use route model binding
https://laravel.com/docs/8.x/routing#route-model-binding
And better to use named routes
Please or to participate in this conversation.