简体   繁体   中英

How to delete from the database using JQuery and Laravel

I have the following code with an if statement depending if a user has saved an article or not. I'm simply trying to delete the article from the database using jquery. I unsure where im going wrong? help is much appreciated!

View:

<form action="{{URL::route('article-delete')}}" method="post" id="article_one_delete">
<div class="form-group">
<input type="hidden" name="first_desc" value="{{$firstrow->description}}" class="form-control">
</div>
<div class="form-group">
<input type="hidden" name="first_title" value="{{$firstrow->title1}}" class="form-control">
</div>

<button type ="button" id="Recodelete" class="btn btn-success btn-xs">UnSave</button>
{{Form::token()}}

</form>

Route:

Route::delete('/home/', array( 'as' => 'article-delete', 
'uses' => 'HomeController@deletearticle'));

Controller:

public function deletearticle(){

 $firsttitle       = Input::get('first_title');

$articledelete  = UserSaveArticle::where('user_id', Auth::id()
 ->where ('user_save_articles.chosen_title', $firsttitle))->delete();

return true;

JQuery:

$(document).ready(function(){
    $('#Recodelete').on('click', function(){
       var article_one_delete = $('#article_one_delete').serializeArray();
       var url_d         = $('#article_one_delete').attr('action');

       $.get(url_d, article_one_delete, function(data){
           console.log(data);
       });
    });
 });
  1. You should define right route for DELETE article, like this:
Route::delete('/article/{id}', ['as' => 'article-delete', 'uses' => 'HomeController@deleteArticle']);
  1. In the HomeController $id variable (article ID) will be available as a method parameter:
function deleteArticle($id)
{
    …
}
  1. In PHP side you defined DELETE route, it means you should make DELETE request on JS side using the ajax method:
$.ajax({
    url: '/article/' + articleId,
    type: 'DELETE',
    success: function(result) {
        // Do something with the result
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM