Oussama GHAIEB

Tips, tricks, and code snippets for developers

Integrating PHPWord with a Laravel Project

PHPWord is a robust library that allows developers to create, read, and write Word documents programmatically. By integrating it into a Laravel project, you can automate tasks such as generating reports, invoices, or any Word document directly from your application.

This guide walks you through the steps to integrate PHPWord into your Laravel application.

Prerequisites

  • A Laravel project (version 8.x or later recommended).
  • Composer installed on your development machine.
  • Basic knowledge of Laravel controllers, routes, and views.

Step 1: Install PHPWord

First, install PHPWord using Composer:

composer require phpoffice/phpword

This will add PHPWord to your project’s dependencies.


Step 2: Create a Service Class for PHPWord

To keep the logic clean, create a dedicated service class for handling PHPWord-related tasks.

Manually create a file for the service class:

mkdir -p app/Services && touch app/Services/PHPWordService.php

Edit the newly created PHPWordService.php file:

namespace App\Services;

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;

class PHPWordService
{
    protected $phpWord;

    public function __construct()
    {
        $this->phpWord = new PhpWord();
    }

    public function createDocument(string $fileName, array $data): string
    {
        $section = $this->phpWord->addSection();

        foreach ($data as $text) {
            $section->addText($text);
        }

        $filePath = storage_path("app/{$fileName}.docx");
        $writer = IOFactory::createWriter($this->phpWord, 'Word2007');
        $writer->save($filePath);

        return $filePath;
    }
}

Step 3: Configure a Controller

Create a controller to use the service class for generating Word documents.

Run the following command:

php artisan make:controller DocumentController

Edit the DocumentController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\PHPWordService;

class DocumentController extends Controller
{
    protected $phpWordService;

    public function __construct(PHPWordService $phpWordService)
    {
        $this->phpWordService = $phpWordService;
    }

    public function generate(Request $request)
    {
        $validated = $request->validate([
            'file_name' => 'required|string|max:255',
            'content' => 'required|array',
        ]);

        $filePath = $this->phpWordService->createDocument($validated['file_name'], $validated['content']);

        return response()->download($filePath)->deleteFileAfterSend(true);
    }
}

Step 4: Add a Route

Define a route to handle document generation.

In routes/web.php:

use App\Http\Controllers\DocumentController;

Route::post('/generate-document', [DocumentController::class, 'generate']);

Step 5: Create a View (Optional)

If you want a front-end interface to generate documents, create a view with a form.

In resources/views/generate-document.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Word Document</title>
</head>
<body>
    <h1>Generate Word Document</h1>
    <form action="/generate-document" method="POST">
        <input type="hidden" name="_token" value="CWaqT56unDNC7uQ8OIru2RDKOxzQeKg25ntdoQBE" autocomplete="off">        <label for="file_name">File Name:</label>
        <input type="text" id="file_name" name="file_name" required>

        <label for="content">Content:</label>
        <textarea id="content" name="content[]" required></textarea>

        <button type="submit">Generate</button>
    </form>
</body>
</html>

Step 6: Test the Integration

Start your Laravel development server:

php artisan serve

Visit the form page (if created) or send a POST request to /generate-document with appropriate data using a tool like Postman.

Example POST request body:

{
    "file_name": "example",
    "content": ["Hello, World!", "This is a test document."]
}

Once submitted, the generated Word document should download automatically.


Conclusion

Integrating PHPWord into your Laravel project enables powerful document management capabilities. By following this guide, you’ve set up a reusable service class and controller to dynamically generate Word documents. Expand on this foundation to include more advanced features like styling, tables, or images.

Happy coding!

Tags: #laravel #packages
Oussama GHAIEB - Laravel Certified Developer in Paris

Oussama GHAIEB

Laravel Certified Developer | Full-Stack Web Developer in Paris

14+ years experience 20+ projects
Read more about me →

Comments (0)

No comments yet. Be the first to comment!


Leave a Comment

More Posts :