Home > Blockchain >  insert array to database with query builder and unset array when find same value
insert array to database with query builder and unset array when find same value

Time:10-03

im want to insert array to db with query builder on laravel controller, and i get error, I also haven't found a way to prohibit the same data from entering the database

my foreach :

  $like = '123';
  foreach($list as $data) {
    $filter = array_filter($data, function ($item) use ($like) {
        if (stripos($item['number'], $like) !== false) {
           return true;
        }
        return false;
    });
  }

im trying to dd($filter); and get array like this :

^ array:3 [▼
1 => array:2 [▼
    "number" => "123"
    "desc" => "tester1"
]
2 => array:2 [▼
    "number" => "578"
    "desc" => "tester2"
]
4 => array:2 [▼
    "number" => "123"
    "desc" => "tester3"
]

my query builder

   DB::table('myData')->insert(
     ['number' => $filter['number'], 'desc' =>$filter['desc']
   );

error log in line $filter['number']:

Undefined index: number

CodePudding user response:

You have to use foreach loop:

foreach($filter as $item)
{
    DB::table('myData')->insert(
         ['number' => $item['number'], 'desc' =>$item['desc']
    );
}

CodePudding user response:

As I can see you have a multidimensional array, so you have to run two foreach loops to access the number index

$like = '123';
  foreach($list as $data) {
    $filter = array_filter($data, function ($item) use ($like) {
        foreach($item as $value) {
            if (stripos($value['number'], $like) !== false) {
           return true;
        }
        return false;
        }
        
    });
  }

CodePudding user response:

In a more simpler way, As your output is

array:3 [▼
1 => array:2 [▼
    "number" => "123"
    "desc" => "tester1"
]
2 => array:2 [▼
    "number" => "578"
    "desc" => "tester2"
]
4 => array:2 [▼
    "number" => "123"
    "desc" => "tester3"
] 

which has the same index as table columns, so you can just pass $filter into insert method. eg.

DB::table('myData')->insert($filter);

This will handle multiple records insert. for more help https://laracasts.com/discuss/channels/eloquent/insert-multiple-records-in-one-query

  • Related