mafortis
mafortis

Reputation: 7128

Laravel sending multiple id to controller by ajax

I want to make multiple delete in laravel 5.5, I have tried forms it didn't work so i decided to use ajax instead.

What I try to do:

  1. Use checkbox to select multiple post/product id's.
  2. Send them to controller by ajax.
  3. Delete them.

Codes

controller

public function multipledel(Request $request){
      $deli = $request->input('productsfordel'); //get id's of selected post/products
      $product = Product::where('id', [$deli]); //find those id's in DB
      $product->delete(); // Delete them

      Session::flash('success', 'Selected products are successfully deleted.');
      return redirect()->route('products.index');
    }

route

Route::post('delmultipleproducts', 'ProductController@multipledel')->name('delmultipleproducts');

ajax

<script type="text/javascript">
  $(document).ready(function() {
    $('#multidel').on('click', function(e) {  //define which button to click for multiple delete
      e.preventDefault();
      $.ajaxSetup({
          headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
      });

      var idss = $('#productsfordel').val(); //where to get id's from
      if(idss) {
      $.ajax({
        url: '{{ url('admin/delmultipleproducts') }}',
        type: "POST",
        dataType: "json",
        success:function(data) {
          console.log('working');
        }
      });
      }else{
        console.log('not working');
      } 
    });
  });
</script>

blade

<button id="multidel" name="multidel">Delete All</button>

<thead>
  <th class="text-center">xxxxx</th>
</thead>
<tbody>
  @foreach($products as $product)
  <tr>
    <td>
      <input type="checkbox" id="productsfordel" name="productsfordel[]" value="{{ $product->id }}" />
    </td>

// rest of table

Issues

this is what i get in my network as result:

screen 1

Any idea?

UPDATE

Base on Babak answer I can get some result on network which means id's are actually sending, here is error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`mysite`.`product_relatives`, CONSTRAINT `product_relatives_product_id_foreign` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)) (SQL: delete from `products` where `id` = 48)

so I realize it must have to do something with my products sync method such as options and specification and i changed my function to:

public function multipledel(Request $request){
      $deli = $request->input('productsfordel');
      $product = Product::where('id', [$deli]);
// added from here
      $product->suboptions()->detach();
      $product->subspecifications()->detach();
      if(!empty($product->imageOne)){
        Storage::delete($product->imageOne);
      }
      if(!empty($product->imageTwo)){
        Storage::delete($product->imageTwo);
      }
//to here
      $product->delete();

      Session::flash('success', 'Selected products are successfully deleted.');
      return redirect()->route('products.index');
    }

now i'm getting:

Call to undefined method Illuminate\Database\Query\Builder::suboptions()

any idea?

Upvotes: 1

Views: 2626

Answers (3)

Asadullah AbdulJabbar
Asadullah AbdulJabbar

Reputation: 81

Ajax call and select the multiple values

 var id=[];
            $('.subcheckes').each(function(){
               var values=$(this).attr('value')
                id.push(values)
            });                
            var url ="{{route('routeName')}}"
           var token = $("meta[name='csrf-token']").attr("content");
 
  $.ajax({
                   url: url,
                    type: 'POST',
                    data: {
                       "id": id,
                       "_token": token,
                   },
                    success: function(result) {
                       // Do something with the result
 
                      console.log('first')
                       $('#dataTable').DataTable().ajax.reload();
                    },
                    error:function(e){
                        console.error(e);
                    }
                });
                Swal.fire(
 
                    'Deleted!',
                    'Your file has been deleted.',
                    'success'
                )

Controller

    public function selectedData(Request $request)
    {
      $ids=$request->id;
       $categories=Category::whereIn('id',$ids)->get();
        foreach ($categories as $key => $category) {
            $category->delete();
        }

    }

Upvotes: 0

user9648303
user9648303

Reputation:

You are giving your inputs the same id: not a good idea. First ou should remove the id attribute from your input tags.

Then you'd better enclose your inputs in a form tag with an id (let's say "myForm"):

<form id="myForm">
    <table>
    // ...
    @foreach($products as $product)
        <tr>
            <td>
                <input type="checkbox" id="productsfordel" name="productsfordel[]" value="{{ $product->id }}" />
            </td>
    // ...
    </table>
</form>

There's no need to set any action method since the route is defined within your Ajax request.

talking about your Ajax request, don't forget to pass your data (i.e you array of ids) with the data property like this:

...
dataType: "json"
data : $('#myForm').serialize()

So the controller receives an array of ids that you can delete with the Eloquent's destroy method :

Product::destroy($request->input('productsfordel'));

EDIT: If you don't want to use a form, you could instead give your inputs a class instead of an id (class="someClass") and then pass your data with

data: $('.someClass:checked').serialize(),

Upvotes: 1

Babak Asadzadeh
Babak Asadzadeh

Reputation: 1239

First of all add data to your ajax

  var idss = $('#productsfordel').val();
  if(idss) {
  $.ajax({
    url: '{{ url('admin/delmultipleproducts') }}',
    type: "POST",
    dataType: "json",
    data: {
    productsfordel: idss
    }
    success:function(data) {
      console.log('working');
    }
  });
  }else{
    console.log('not working');
  } 

Then add a foreach in your controller like this

    $deli = $request->get('productsfordel'); //get id's of selected post/products
   Foreach($deli as $item){
  $product = Product::find($item); //find those id's in DB
  $product->delete(); // Delete them
    }

Upvotes: 2

Related Questions