# Integrating PHPWord with a Laravel Project

> Author: [Oussama Ghaieb](https://oussama.ghaieb.com/about-me)
> Canonical: https://oussama.ghaieb.com/posts/integrating-phpword-with-a-laravel-project

# <span class="hover:bg-yellow-100">Integrating PHPWord with a Laravel Project</span>

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:

```bash
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:

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

Edit the newly created `PHPWordService.php` file:

```php
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:

```bash
php artisan make:controller DocumentController
```

Edit the `DocumentController`:

```php
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`:

```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`:

```html
<!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="" 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:

```bash
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:

```json
{
    "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!
