> ## Documentation Index
> Fetch the complete documentation index at: https://docs.markpdf.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel

> Controller en Laravel para convertir documentos.

# Laravel

## Controller

```php theme={null}
<?php
// app/Http/Controllers/ConvertController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ConvertController extends Controller
{
    public function convert(Request $request)
    {
        $request->validate(["file" => "required|file|max:12288"]);

        $file = $request->file("file");
        $apiUrl = config("services.flash_md.url");
        $apiKey = config("services.flash_md.key");

        $response = Http::timeout(300)
            ->withHeaders([
                "x-api-key" => $apiKey,
                "content-type" => $file->getMimeType(),
            ])
            ->withBody($file->getContent(), $file->getMimeType())
            ->post("{$apiUrl}/convert/raw?filename=" . urlencode($file->getClientOriginalName()) . "&mode=fast");

        if ($response->status() === 200) {
            return response($response->body(), 200)
                ->header("Content-Type", "text/markdown; charset=utf-8");
        }

        if ($response->status() === 202) {
            $job = $response->json();
            $markdown = $this->pollJob($apiUrl, $apiKey, $job["job_id"]);
            return response($markdown, 200)
                ->header("Content-Type", "text/markdown; charset=utf-8");
        }

        return response($response->body(), $response->status());
    }

    private function pollJob(string $apiUrl, string $apiKey, string $jobId): string
    {
        while (true) {
            sleep(5);
            $res = Http::timeout(30)
                ->withHeaders(["x-api-key" => $apiKey])
                ->get("{$apiUrl}/jobs/{$jobId}");

            $data = $res->json();

            if ($data["status"] === "completed") {
                return $data["body"];
            }
            if ($data["status"] === "failed") {
                abort(502, $data["error"] ?? "Job failed");
            }
        }
    }
}
```

## Config

```php theme={null}
// config/services.php
'flash_md' => [
    'url' => env('FLASH_MD_API_URL', 'https://api.markpdf.tech'),
    'key' => env('FLASH_MD_API_KEY'),
],
```

## Ruta

```php theme={null}
// routes/api.php
Route::post('/convert', [ConvertController::class, 'convert']);
```
