0

Here is my code:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

Obviously my code should insert 5 rows. But surprisingly it inserts only 1 row. What's wrong and how can I fix it?

2
  • 1
    $voucher = new Voucher; is in for loop! Commented Dec 5, 2017 at 8:54
  • @HirenGohel True .. thank you Commented Dec 5, 2017 at 8:55

5 Answers 5

2

You are always using the same instance of the object. Each time you save the same row with different data. here is how to fix.

$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should create a new voucher within the for-loop. Currently, as you said, you are inserting the same object into the database five times

Comments

1

You are using same instance everytime! Create new one in every for loop like:

$num = 5;

for ( $i = $num; $i > 0; $i-- ) {

    $voucher = new Voucher;

    $token = generateRandomString(5, ['number', 'uppercase']);

    $voucher->prefix = $request->prefix;
    $voucher->token = $token;
    $voucher->description = $request->description;
    $voucher->date_time = time();
    $voucher->save();
}

Comments

1

This is basic example create multi array and simply put in insert function.

$num = 5;
$dataArray = array();
for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $dataArray[$i]['prefix'] = $request->prefix;
    $dataArray[$i]['token'] = $token;
    $dataArray[$i]['description'] = $request->description;
    $dataArray[$i]['date_time'] = time();

}

Voucher::insert($dataArray); 

Comments

0

If you already have a model instance, you may use the fill method to populate it with an array of attributes:

$num = 5;
$voucher = new Voucher;

for ( $i = $num; $i > 0; $i-- ) {

    $token = generateRandomString(5, ['number', 'uppercase']);

    $payload = [];
    $payload['prefix'] = $request->prefix;
    $payload['token'] = $token;
    $payload['description'] = $request->description;
    $payload['date_time'] = time();

    $voucher->fill($payload);
}

Documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.