Home > Back-end >  Best way to bulk create models within Laravel?
Best way to bulk create models within Laravel?

Time:10-21

I am creating a feature which involves creating voucher codes for discounts. I contain an input which the user can fill out with the specific amount they want.

When it hits the store method say if the user has entered 15 vouchers how would you create that many model records in one go?

From looking at the laravel documentation the only thing i've seen is using factories so i've attempted this below.

public function storeCodes(Request $request, VoucherGroup $voucherGroup)
{
    VoucherCode::create([
        'code' => $this->generateUniqueCode(),
        'group_id' => $voucherGroup->id,
        'used' => 0
    ]);

    session()->flash('success', 'successfully created codes.');

    return back();
}

 private function generateUniqueCode()
    {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersNumber = strlen($characters);
        $code = '';

        while (strlen($code) < 6) {
            $position = rand(0, $charactersNumber - 1);
            $character = $characters[$position];
            $code = $code . $character;
        }

        if (VoucherCode::where('code', $code)->exists()) {
            dd('lol');
            $this->generateUniqueCode();
        }

        return $code;
    }

Input

<x-inputs.input size="6" type="number" name="voucher_amount" required>How many Voucher codes do you want
                to
                generate?
            </x-inputs.input>

The problem is it creates the models but the code returns the same code for each model.

How would I create 15 models in one call with unique code fields?

CodePudding user response:

The for loop below solved this for me. It was originally posted by someone but its been deleted recently so ill answer the question below but thanks to whoever provided it!

$newVouchers = [];
        for ($i = 0; $i < $request->voucher_amount; $i  ) {
            $newVouchers[] = VoucherCode::create([
                'code' => $this->generateUniqueCode(),
                'group_id' => $voucherGroup->id,
                'used' => 0
            ]);
    }

CodePudding user response:

You can try it shortly

do {
    //generate unique code
    $uniqueCode = strtoupper(substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 15));
} while (VoucherCode::where('code', $uniqueCode)->exists());

VoucherCode::create([
    'code' => $uniqueCode,
    'group_id' => $voucherGroup->id,
    'used' => 0
]);

session()->flash('success', 'successfully created codes.');

return back();
  • Related