V4n1ll4
V4n1ll4

Reputation: 6099

Laravel 5 using PhpWord to generate multiple documents and ZIP

I am using PhpWord to generate multiple documents on the fly, but at the moment it quits out after just creating one document. For example, the below coupon loop has 3 items in the array so it should create 3 separate documents - only 1 gets created.

Also, once the documents are created, I want to compress al 3 into a ZIP file. Is this possible with Laravel?

The code I am using is:

    $phpWord = new \PhpOffice\PhpWord\PhpWord();

    foreach($request->get('order') as $id) 
    {
        $coupons = $coupon->whereOrderNumber($id);

        if($coupons->count() == 0)
        {
            // only happens when customer has not bought a voucher
            return Response::json(array('error' => true, 'title' => 'Error!', 'msg' => 'This customer has not purchased a voucher and therefore a voucher letter cannot be generated.'));
        }

        foreach($coupons->get() as $coupon) 
        {
            $filename = 'Voucher-'.time().'.docx';
            $document = $phpWord->loadTemplate(storage_path('templates/voucher.docx'));
            $document->setValue('code', $coupon->code);
            $document->saveAs(storage_path('exports/'.$filename));
        }
    }

Does anyone know how I can generate multiple documents in the loop?

Upvotes: 0

Views: 2156

Answers (1)

cre8
cre8

Reputation: 13562

time()

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

So if your script is really fast the files will be overwritten. You can use a counter and add a value to it like this:

foreach($coupons->get() as $key => $coupon) 
    {
        $filename = 'Voucher-'.time().' - '. $key . '.docx';
        $document = $phpWord->loadTemplate(storage_path('templates/voucher.docx'));
        $document->setValue('code', $coupon->code);
        $document->saveAs(storage_path('exports/'.$filename));
    }

To zip the docs you can use https://github.com/Chumper/Zipper

$zipper->make('test.zip')->folder(storage_path('exports'));

Upvotes: 1

Related Questions