Ad

Generate More Than One Random Code In Laravel And Save It To Database

- 1 answer

I'm a newbie in laravel. I have to generate multiple random characters at once in my laravel project and then save them to database. Any example or advise that quite easy to understand? thank you

Ad

Answer

A for loop may be appropriate for you in this case. If you don't have an object for the codes, you can do something like this:

$total_wanted = 100;
for ( $i = 0; $i < $total_wanted; $i++ ) {
    DB::table('codes')->insert(['code' => uniqid("prefix")]);
}

If you do have a Code object, you can do it like this instead:

$total_wanted = 100;
for ( $i = 0; $i < $total_wanted; $i++ ) {
    $code = new Code;
    $code->code = uniqid("prefix");
    $code->save();
}
Ad
source: stackoverflow.com
Ad