Laravel通过 AJAX 发送多个id到控制器

tct7dpnv  于 2023-03-04  发布在  其他
关注(0)|答案(3)|浏览(197)

我想在laravel 5.5多删除,我已经尝试过的形式,它不工作,所以我决定使用ajax代替。

我尝试做的事情:

1.使用复选框选择多个发布/产品ID。
1.通过ajax将它们发送到控制器。
1.删除它们。

代码

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

问题

这是我在我的网络中得到的结果:

你知道吗?

更新

根据Babak答案,我可以在网络上获得一些结果,这意味着ID实际上正在发送,以下是错误:

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)

所以我意识到它必须与我产品同步方法(如选项和规范)有关,我将我的函数更改为:

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');
    }

现在我得到了:

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

你知道吗?

fdbelqdn

fdbelqdn1#

首先,将数据添加到 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');
  }

然后在控制器中添加一个foreach,如下所示

$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
    }
cigdeys3

cigdeys32#

您为输入指定了相同的ID:这不是个好主意。2首先你应该从你的输入标签中删除id属性。
然后,最好将输入包含在一个带有id的form标记中(比如“myForm”):

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

由于路由是在 AJAX 请求中定义的,因此不需要设置任何操作方法。
谈到 AJAX 请求,不要忘记使用data属性传递数据(即id数组),如下所示:

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

因此,控制器接收一个id数组,您可以使用Eloquent的destroy方法删除该数组:

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

EDIT:如果您不想使用表单,您可以为输入指定一个class而不是id(class=“someClass”),然后使用

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

ffx8fchx3#

  • AJAX 调用并选择多个值 *
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'
                )
  • 主计长 *
public function selectedData(Request $request)
    {
      $ids=$request->id;
       $categories=Category::whereIn('id',$ids)->get();
        foreach ($categories as $key => $category) {
            $category->delete();
        }

    }

相关问题