PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 26, 2022

[FIXED] Foreach insert Laravel 5 Eloquent

 January 26, 2022     eloquent, laravel-5, php     No comments   

Issue

Trying to insert records using a foreach loop.

$test = array(123, 231, 321, 543);

foreach($test as $key) {
    $data = array('name' => 'test_name', test' => $test[$key], 'property' => 'test_property');
    Test_table::insert($data);    
}

Using a foreach gives an error Undefined offset: 123.

Inserting this way works though:

 $data = array(
    array('name' => 'test_name', test' => 123, 'property' => 'test_property'), 
    array('name' => 'test_name', test' => 231, 'property' => 'test_property'), 
    array('name' => 'test_name', test' => 321, 'property' => 'test_property'), 
    array('name' => 'test_name', test' => 543, 'property' => 'test_property'),
  );
 Test_table::insert($data);  

What is wrong?


Solution

$test = array(123, 231, 321, 543);
foreach($test as $key) {
    $data = array('name' => 'test_name', 'test' => $key, 'property' => 'test_property');
    Test_table::insert($data);    
}

This should work. You don't need to access $test by index since you already have the value in $key which is in fact a value from the array.



Answered By - MichaelK
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing