Here is my view:
<a href="/article/{{$articles->id}}" data-id="{{$articles->id}}">delete</a>
Here are my scripts:
$('.js-ajax-deleteConfirm').click(function () {
let deleteConfirm = confirm('are you sure?');
if (deleteConfirm == true) {
let clickEle = $(this)
let id = clickEle.attr('id');
$.ajax({
url: '/articles/' id,
type: 'POST',
data: {
"_token": "{{ csrf_token() }}",
'id': id,
'_method': 'DELETE'
}
})
}
});
Here is my route:
Route::delete('/articles/{id}', 'ArticleController@delete')->name('delete');
Here is my controller:
public function delete($id)
{
$articles = Article::findOrFail($id);
$articles->delete();
return redirect()->route('articles_index')->with('msg_success', 'deleted');
}
How can I solve this? I cant delete article. after i hit delete and yes/no button, it just shows me "Sorry, the page you are looking for could not be found."
CodePudding user response:
You are posting to your Backend. The route is defined with the Http DELETE method.
Route::delete(...);
Therefor you have to use it, like so.
$.ajax({
url: '/articles/' id,
type: 'DELETE',
data: {
"_token": "{{ csrf_token() }}",
'id': id
}
})
The _delete property, is a option to solve that forms can only POST. When you are using jQuery, you have to use the proper Http methods.
CodePudding user response:
Make changes as per below code
in route file
Route::delete('/articles/{id}', 'ArticleController@delete')->name('articles.delete');
in blade file
<a href="javascript:void(0)" data-id="{{ $articles->id }}" data-url="{{ route('articles.delete', ['id' => $articles->id]) }}">delete</a>
js code
$('.js-ajax-deleteConfirm').click(function () {
if(confirm('are you sure?')){
var url = $(this).attr('data-url');
var id = $(this).attr('data-id');
$.ajax({
url: url,
type: 'DELETE',
data: {
"_token": "{{ csrf_token() }}",
'id': id,
}
})
}
});