B
B
BonBon Slick2016-11-08 15:38:37
JavaScript
BonBon Slick, 2016-11-08 15:38:37

No query results for model, ajax single row delete Laravel 5.3?

Ajax request:

$(document).on('click', '.delete_single', function(){
         var id = $(this).data("id");
         var token = $(this).data("token");

         $.ajax({
           url: "/product/"+id+"/delete",
           type: 'delete',
           data: {
             "id": id,
             "_method": 'delete',
             "_token": token,
           },
           success: function ( response ){
             console.log("Success! Row deleted.");
           },
           error: function(){
             console.log("ERROR!");
           },
         });
         $(this).parents('tr').remove();
       });

Route
Route::delete( 'product/{product_id}/delete', '[email protected]' );

Controller
public function delete(Product $product)
{
  if( exists( $product ) && !empty( $product ) )
  {
    $product->delete();
  }
}

product_id was bound as a model.
Route::model('product_id ', Product::class);

How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Semenko, 2016-11-08
@BonBonSlick

1. Not easier to add an attribute to .delete_single

data-delete="{{ route('products.delete', ['product' => $product]) }}"
and then use it in a query?
2. Why use the name product_id instead of product? Without this, you can use Route::resource
3. Do you prescribe a token in each request? Maybe you should learn about ajaxSetup ?
4. Why pass id and _method in data if id is in the link, and the request type is determined based on type: "DELETE"?
5. exists( $product ) && !empty( $product )- why is this? Laravel itself checks the existence of a record in the database with the passed id
6. You need to give at least something in response: return response()->json($product->delete())
If all these remarks are taken into account, then the error will disappear, as it seems to me :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question