skip to Main Content

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

3

Answers


  1. You have to use foreach loop:

    foreach($filter as $item)
    {
        DB::table('myData')->insert(
             ['number' => $item['number'], 'desc' =>$item['desc']
        );
    }
    
    Login or Signup to reply.
  2. 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;
            }
            
        });
      }
    
    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search