Download the PHP package pavelzanek/laravel-deepl without Composer

On this page you can find all versions of the php package pavelzanek/laravel-deepl. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-deepl

Laravel Deepl

Latest Version on Packagist Total Downloads GitHub Issues License

Table of Contents

Introduction

Laravel Deepl is a Laravel package that serves as a wrapper for the official DeepL PHP client, enhancing it with additional features such as caching and chainable translation methods. This package leverages the robustness of the official client while providing a more Laravel-centric interface. For comprehensive details about the DeepL API, including available endpoints and parameters, please refer to the DeepL API Documentation.

Requirements

Before installing and using this package, please ensure your environment meets the following minimum requirements:

These versions are required to ensure compatibility with the package and the features it provides. Make sure your project is running on these versions or higher before integrating this package.

Installation

You can install the package via Composer:

Configuration

To publish the configuration file, run:

This will create a config/laravel-deepl.php file where you can set your DeepL API key and other configuration options.

Migrations

The package includes a migration that creates the translations table used for caching translations (more info: Text Translation). To publish the migration files, run:

This command will copy the migration files to your application’s database/migrations directory.

After publishing the migrations, you need to run them to create the necessary database tables:

This will execute the migration and create the translations table in your database, enabling the caching feature.

Environment Variables

Add your DeepL API key to your .env file:

Other environment variables you might want to set:

Usage

Usage Options: Facade vs. Client

The package offers two primary ways to interact with the DeepL API: using the Facade or directly using the DeeplClient class. Additionally, the translateText method now supports method chaining, allowing for more flexible and readable translation requests.

Using the Facade:

Using the DeeplClient:

Note: The result is returned as an object from the official DeepL API PHP package. For more details on the response structure, refer to the official documentation.

Text Translation

You can easily translate text using the provided client:

Example Using the Facade:

Example Using the DeeplClient:

Basic Usage Example of DeeplClient for Translating Text:

Integrating DeeplClient into a Laravel Controller for example:

Method Chaining

When utilizing the chainable methods provided by the translateText function, do not pass the text as an argument. Instead, call translateText without any parameters to receive a builder instance that allows method chaining. Passing the text directly will bypass the builder and prevent the use of chainable methods.

The translateText method supports method chaining, allowing you to set additional options and parameters in a more readable and concise way:

Example Using the Facade:

Example Using the DeeplClient:

Available Chainable Methods

The translateText method returns a builder instance that allows you to chain the following methods:

Using the options Parameter

The translateText method accepts an optional options array as its fourth argument, allowing you to specify additional translation settings. Alternatively, you can use chainable methods to set these options.

Using Chainable Methods

Caching Translations

The package includes a caching mechanism that stores translations in the database to optimize performance and reduce the number of API calls to DeepL. This can be especially useful when translating the same text multiple times or when working with large volumes of text.

Running the Migration

Before you can use the caching feature, you need to publish and run the migration that creates the translations table in your database:

This will create the necessary table where translations will be stored.

How Caching Works

When you request a translation, the package checks if the translation already exists in the database before making an API call to DeepL. This is controlled by the useCache property.

Customizing Cache Behavior

The caching mechanism uses the TranslationCache model to store the translated texts. The cache table name can be customized via the DEEPL_TRANSLATION_CACHE_TABLE environment variable. By default, it is set to translations_cache.

This option can also be set directly in the configuration file:

Disabling this option means that every translation request will result in an API call to DeepL, which could increase your API usage costs.

Benefits of Caching

The caching feature is a powerful tool for optimizing your application’s localization workflow, ensuring that translations are both fast and cost-effective.

Important Note on Caching and Options

The translation cache is sensitive to the options used in the translation request. Any change in the options (such as formality, splitSentences, preserveFormatting, etc.) will lead to a different cache entry. Ensure that you consider this when working with translations that require specific options, as the cache will reflect these variations.

In the first case, the translation is performed with default settings. In the second case, the translation includes the formality option set to less. Even though both translations are for the same text and languages, they will produce different results and therefore be cached separately.

Example Usage

In this example, the translation of “Hello, world!” from English to German is either retrieved from the cache or, if not cached, obtained from DeepL and then stored in the cache for future use.

Disabling Cache

If you need to bypass the cache and always make a fresh API call, you can use the withoutCache method:

Using the useCache Parameter:

The translateText method includes a fifth parameter, useCache, which determines whether to utilize the translation caching mechanism. This parameter is optional and defaults to the value specified in your configuration (config('laravel-deepl.enable_translation_cache')).

Using the useCache Parameter Directly:

Using Chainable Methods:

Single vs. Multiple Texts

The TranslationBuilder provides two methods for setting the text to translate:

Example Using text() for a Single Text:

Example Using texts() for Multiple Texts:

By utilizing the text() and texts() methods appropriately, you can efficiently handle both single and multiple translation requests within your application.

Document Translation

You can also translate documents using the provided client or facade.

Example Using the Facade:

Example Using the DeeplClient:

Method Chaining for Document Translation

With the introduction of the DocumentTranslationBuilder, you can now perform document translations using chainable methods, making your code more organized and readable. Do not pass the inputFile and outputFile directly as arguments when using chainable methods. Instead, use the builder to set these paths along with other optional parameters.

Example Using the Facade:

Example Using the DeeplClient:

Available Chainable Methods for Document Translation:

The DocumentTranslationBuilder provides the following chainable methods:

Additional Features

The underlying DeepL PHP API offers more advanced options for document translation, such as specifying translation formality, using glossaries, or enabling document minification for larger files (e.g., PowerPoint presentations with many images).

For example, you can use the translateDocument method to set formality or enable document minification:

Document minification helps to reduce the size of the document before translation by removing or compressing large media files, ensuring that the file meets the DeepL API size limits. For more details on supported file types, media formats, and additional options, please refer to the DeepL PHP API documentation.

Glossary Management

You can create, retrieve, list, and delete glossaries using the provided client or facade. With the introduction of the CreateGlossaryBuilder, creating glossaries has become more flexible and streamlined through method chaining.

Creating a Glossary

Example Using the Facade:

Example Using the DeeplClient:

Method Chaining for Glossary Creation

Example Using the Facade with CreateGlossaryBuilder:

Example Using the DeeplClient with CreateGlossaryBuilder:

Adding Multiple Glossary Entries

You can add multiple glossary entries either by passing an associative array or by using a GlossaryEntries object.

Adding Entries Using an Associative Array:

Adding Entries Using a GlossaryEntries Object:

Summary of Available Methods in CreateGlossaryBuilder

Additional Features

The official DeepL API offers advanced functionality for glossary management, such as uploading glossaries from CSV files and listing glossary entries. You can also use stored glossaries for both text and document translation.

CSV Glossary Example:

To see all stored glossaries, retrieve glossary entries, or use glossaries in translations, refer to the DeepL PHP API documentation.

Language Support

You can list all supported source and target languages, including details about which target languages support the formality option, and you can also retrieve supported glossary language pairs.

Example Using the Facade:

Example Using the DeeplClient:

Chainable Methods for Language Support

Leveraging the LanguageBuilder for a more fluent and flexible approach.

Available Chainable Methods

The LanguageBuilder provides the following chainable methods:

Usage Limits

Monitoring your API usage is essential to ensure that you do not exceed your DeepL plan limits. The package provides mechanisms to retrieve and display usage information.

Retrieving Usage Information

You can retrieve the current usage and quota information from the DeepL API to monitor your translation usage:

This will return an object containing details about your API usage, including the number of characters translated and any other relevant quota limits.

Usage Command

The package provides an Artisan command to retrieve and display usage information directly from the command line.

Command Syntax:

Example Output:

Command Details

The deepl:usage command retrieves usage information within the current billing period along with account limits. It displays the data in a formatted table, highlighting usage types that are approaching or have exceeded their limits.

Handling Different Usage Types

The command can display various usage types, such as:

Each usage type includes the count, limit, remaining quota, and the percentage of the limit used.

Color-Coded Warnings

Translating Localization Files

The package includes a convenient Artisan command for translating Laravel localization files using the DeepL API. This allows you to quickly translate your application’s language files from one language to another. However, it’s always important to review the generated translations and verify their correctness. Human oversight is crucial to ensure that translations are accurate, appropriate, and contextually relevant for your application.

Translating a Single Localization File

Command Syntax

You can use the command as follows:

Example

To translate a file from English to Czech, you can run:

This will create a translated file at lang/cs/messages.php, preserving the structure and formatting of the original file.

Translating Entire Localization Folders

Command Syntax

To translate all localization files within a folder (including subdirectories), use the following command:

Example

To translate all files in the English localization folder to Czech, run:

This command will recursively traverse all files and subdirectories within lang/en, translating each file and saving the translated versions in the corresponding target language directory (e.g., lang/cs).

Laravel 10 and Below Compatibility

In Laravel 10 and earlier versions, the localization files are stored in resources/lang. This package supports both Laravel 10 (or below) and Laravel 11. To ensure compatibility, use the appropriate folder path when running the commands:

Example

Laravel 11:

Laravel 10 and below:

This package will check both paths (lang/ and resources/lang/) and will prevent translating the root folder, ensuring only subdirectories (like lang/en or resources/lang/en) are translated.

Handling the Root lang Folder

When using the deepl:translate-folder command, the package automatically skips translating the root lang folder (or resources/lang in Laravel 10 and below). This is because translating the entire lang directory is not recommended. Instead, you should specify a subfolder, such as lang/en or resources/lang/en, to translate localization files for a specific language. If the root lang folder is provided, the command will skip it and display a warning without interrupting the process.

Handling JSON and PHP Files

Both commands support both JSON and PHP localization files. They will automatically detect the file type based on the file extension and handle the translation appropriately.

Important Note on Localization File Structure

It’s important to note that examples like lang/en/messages.json used in this documentation are purely illustrative. While it’s technically possible to structure your localization files this way, the recommended approach, especially for JSON-based translations, follows a different convention. Laravel encourages storing language-specific JSON files directly in the root of the lang folder, such as lang/en.json, lang/cs.json, etc., where each file represents translations for a specific language. This method allows for easier management of translations across multiple languages, without needing separate subdirectories for each language. By adhering to this structure, Laravel can automatically detect the appropriate JSON file based on the language setting and ensure that the translations are loaded correctly. This best practice also streamlines the process of adding new languages, as you simply need to create a new JSON file for the target language, such as fr.json for French, and fill in the necessary translations.

Example of Content Before and After Translation (JSON File)

Original File (lang/en/messages.json):

Translated File (lang/cs/messages.json):

Example of Content Before and After Translation (PHP File)

Original File (lang/en/messages.php):

Translated File (lang/cs/messages.php):

Handling Existing Translations

When translating localization files, the commands are designed to be efficient and avoid overwriting existing translations. If a key already exists in the target localization file, the command will skip translating that key. This means that only keys that are not present in the target file will be translated and added.

This behavior is particularly useful when you have previously translated keys or when you want to update your localization files incrementally. By skipping existing keys, the command ensures that your existing translations remain untouched, and only new or missing keys are added.

Example

Suppose you have a target localization file that already contains some translations.

Existing Target File (lang/cs/messages.php):

If you run the translation command:

The command will detect that the keys welcome and greeting already exist in the target file and will skip translating them. It will only translate and add the missing user key.

Updated Target File (lang/cs/messages.php):

In this way, the command preserves your existing translations and focuses on filling in any gaps with new translations.

Placeholders

The command is smart enough to handle placeholders (e.g., :attribute) within your localization strings. It ensures that these placeholders remain unchanged during the translation process, preserving the integrity of your application.

Directory Creation

If the target directory does not exist, the command will automatically create it, ensuring that the translated file is saved in the correct location.

Running Pint Code Formatter

Both commands (deepl:translate and deepl:translate-folder) support the --with-pint option, which allows you to run Pint (a PHP code formatter) after the translation is complete.

Pint will only run if your application is in the local environment. This prevents unintended code formatting changes in production or other environments.

Note: Before using the --with-pint option, make sure that you have Pint installed in your project. Pint is typically installed as a development dependency via Composer. You can install it using the following command:

If Pint is not installed, the command will fail when attempting to run Pint. Ensuring that Pint is installed will allow the code formatter to run successfully after translation.

Example

To translate all files in the English localization folder to Czech and run Pint after translation, use:

On-the-Fly Translation Setup

The package provides an on-the-fly translation feature that dynamically translates missing keys at runtime using the DeepL API. This can be helpful when you want to automatically handle missing translations without pre-generating them.

Registering Custom Translator

To use the on-the-fly translation feature, you need to register a custom translator in your application's AppServiceProvider. This custom translator will replace Laravel's default translation service with one that integrates with this package.

You can add the following code to your AppServiceProvider:

Using the Queue for Translations

If you want the missing translation keys to be processed in the background using Laravel’s queue system, include the register method code snippet in your AppServiceProvider. This will dispatch the translation jobs to the queue, avoiding any delays during runtime.

Without this, the translations will be processed immediately when they are requested, which may cause a delay if there is a high number of missing translations.

Configuration Options

Ensure that the following configuration settings in config/laravel-deepl.php are enabled or adjusted based on your needs:

Enable On-The-Fly Translation:

Translate Outside Local Environment:

On-The-Fly Source Language:

Use Queue for Translation:

These settings allow you to control how on-the-fly translations are handled, including whether they are processed immediately or dispatched to a queue for asynchronous processing.

Helpers

Enumerations

This package provides a set of enumerations (enums) to simplify and standardize the use of certain options and parameters when interacting with the DeepL API. These enums help ensure that your code remains consistent and less prone to errors.

Available Enums

Here are some of the enums included in the package:

Example Usage

You can use these enums to improve code readability and reduce the chance of errors:

Additional Resources

For more in-depth information about the DeepL API, including advanced features and detailed parameter descriptions, please refer to the official DeepL API Documentation.

Testing

To run the tests, use:

The test suite covers various aspects, including:

Linting

You can run PHPStan to ensure code quality:

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

License

The MIT License (MIT). Please see License File for more information.

Support the Developer

If you find this package helpful and would like to support its ongoing development, consider leaving a tip. Your support is greatly appreciated!

Leave a Tip

Thank you for your generosity!

About the Developer

This package is developed and maintained by Pavel Zaněk, a passionate developer with extensive experience in Laravel and PHP development.


All versions of laravel-deepl with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
deeplcom/deepl-php Version ^1.9
guzzlehttp/guzzle Version ^7.0
illuminate/support Version ^11.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package pavelzanek/laravel-deepl contains the following files

Loading the files please wait ....