Laravel query replace new data with old one

Basically this question is following of [link]

As that question got too messy I want to separate the question here.


I have appended rows in my blade where several select box will append and i can choose options of each of them. this data will save in database (Until here everything is good)

The issue

comes when I change one of my selected options and instead of being update it will add all selects as new one.

Screenshot 1




public function spacssendto(Request $request) {
        $this->validate($request, array(
          'product_id' => 'required',
          'subspecifications' => 'required',

        // get all selected option
        $looped = $request->subspecifications;
        $spec = [];
        if(!empty($looped)){ //check if there is any select box without option
          foreach($looped as $sub) {
              $sub = Subspecification::find($sub);
              if (!empty($sub->id)) {
                  $data = (
                      'product_id' => $request->product_id,
                      'subspecification_id' => $sub->id,
                  array_push($spec, $data);
    //   DB::table('product_subspecification')->insert($spec); // save data to database

Screenshot 2

results of dd($spec)


Any idea?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1


I’ve changed my function to code below and now everything working fine

public function spacssendto(Request $request) {
        $this->validate($request, array(
          'product_id' => 'required',
          'subspecifications' => 'required',
        $collection = collect($request->subspecifications)->map(function ($name) {
            return strtoupper($name);
        ->reject(function ($name) {
            return empty($name);
      $product = Product::find($request->product_id);

Hope it help others.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply