1
votes

I have ids in a string through ajax,

example:

"1,2"

and in my controller, I would like to update multiple rows of a product in one query using whereIn with id => [1,2].

ajax:

$('#add_product').click(function() { 
   var id = $('#get_value').val();
    $.ajax({
        type: 'POST',
        url: "{{action('ProductController@updateProduct')}}",
        data: {
        id: id
        },
     success: function(data){
          alert("success");
     }
    });
});

Controller :

public function updateProduct(Request $request){
 $test_value = collect($request->id);
 $updateProduct = Product::whereIn('id',$test_value)
                  ->update(['title' => 'My title']);
}

But i have this error in the network :

SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '1,2' (SQL: update "products" set "title" = "My title" where "id" in (1,2))

3
just dd($test_value) show the output - vishal pardeshi
dd($test_value) show's me => "1,2" - sebastian larsen
@sebastianlarsen have you overcome this problem with my answer? - Chirag Patel
@ChiragPatel, yes thank's it works very well (y) - sebastian larsen

3 Answers

1
votes

In $test_value you are getting values "1,2" as a string so you have to make it array first with using explode() function(what explode() function do is here),

$ids = explode(',',$test_value);

then pass this $ids into your function.

public function updateProduct(Request $request){
    $test_value = $request->id;
    $ids = explode(',',$test_value);
    $updateProduct = Product::whereIn('id',$ids)
                  ->update(['title' => 'My title']);
}
0
votes

You need to remove collect()

public function updateProduct(Request $request){
   $test_value = $request->id;
   $ids = explode( ',',$test_value);
   $updateProduct = Product::whereIn('id',$ids)
              ->update(['title' => 'My title']);
}
-1
votes

You can not update the fields in the table - bulk. You need to update one by one through the foreach

public function updateProduct(Request $request){
 $updateProducts = [];

 foreach((array) $request->id as $id) {
  $updateProducts[] = Product::where('id', $id)
                                      ->first()
                                      ->update(['title' => 'My title']);
 }
}