I am getting a 405 (Method Not Allowed) in Laravel while trying to delete an item using ajax. Someone please help.
Here is my route
Route::get('/home', 'HomeController@index')->name('home'); Route::post('/destroy', 'PagesController@destroy'); Auth::routes();
Here is my ajax code
function confirmDelete(id){ //alert('Delete post id-'+id); $.ajax({ type: 'post', url: 'blogs/destroy', data: {'id' : id}, dataType: 'json', cache: false, success: function(res){ console.log("worked"); alert(res); } }) }
Here is my controller
public function destroy (Request $request){ $id = $request->id; echo json_encode ($id); // $blog = Blog::findorFail ( $id ); // $blog->delete (); // return response(['msg'=>'Post deleted', 'status'=>'success']); // return redirect::to ( '/blogs' )->with ( 'success', 'Post successfully deleted!' ); }
Advertisement
Answer
The reason you’re getting this error is because your request URI /blog/destroy
doesn’t match the route definition /destroy
.
Therefore either change the route to
Route::post('/blog/destroy', 'PagesController@destroy');
or change your request
$.ajax({ type: 'post', url: '/destroy', // ... })