Search code examples
laravelrandomgenerate

generate more than one random code in laravel and save it to database


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


Solution

  • 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();
    }