Download the PHP package wazza/dom-translate without Composer
On this page you can find all versions of the php package wazza/dom-translate. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download wazza/dom-translate
More information about wazza/dom-translate
Files in wazza/dom-translate
Package dom-translate
Short Description A Laravel Package that will use the build-in Blade Directive to define specific phrases for auto-translation before being rendered to the screen.
License MIT
Homepage https://www.wazzac.dev
Informations about the package dom-translate
Laravel Translate Package
A library that leverages Laravel Directives to provide automated translations for all your Blade phrases or words.
Example: Write HTML static data in English and display it in a different language in real-time.
Overview
The library uses three database tables (_domtphrases, _domttranslations, and _domtlanguages) to manage translations efficiently.
- On page load, the system searches for a specific translation using the provided phrase in the
@transl8()
directive from the _domttranslations table.Laravel generally cache views, so if the content of the entire page didn't change, steps 1 - 4 will not fire as the cached view will simply load.
- If the translation is found, it is returned and displayed on the page without making an API call.
- If the translation is not found (not translated yet), the Google Translate API (or another defined provider) is called to retrieve the new translation.
- The newly translated text is then inserted into the database to avoid future API calls for the same phrase.
Note: To ensure quick retrieval of translations, each phrase is hashed and stored in an indexed table column. All searches are performed against this indexed column for optimal performance.
Installation
PHP 8.0 is the minimum requirement for this project.
Follow these steps to install the package:
Register the Service Provider (if not auto-discovered):
Add to bootstrap/providers.php
:
If your package supports Laravel auto-discovery, this step may be optional.
Add DOM_TRANSLATE_GOOGLE_KEY={your_google_api_key}
to your .env
file and run:
Below are all the supported .env
keys with their default values if not provided. The KEY
(i.e., DOM_TRANSLATE_GOOGLE_KEY
) is required.
- If
DOM_TRANSLATE_USE_SESSION
istrue
, translations will be saved in the session and used as the first point of retrieval. - If no translations are found in the session, or if
DOM_TRANSLATE_USE_SESSION
isfalse
, translations will be retrieved from the database, provided they have been previously stored there. - If translations are still not found, or if both
DOM_TRANSLATE_USE_SESSION
andDOM_TRANSLATE_USE_DATABASE
arefalse
, translations will be sourced from a third-party translation service (e.g., Google Translate). - Depending on whether
DOM_TRANSLATE_USE_SESSION
andDOM_TRANSLATE_USE_DATABASE
aretrue
, the retrieved translation will be saved to either the session or the database. - We strongly recommend setting
DOM_TRANSLATE_USE_DATABASE
totrue
(default istrue
if not specified in your .env) to ensure we don't make repeated API calls (also it's slower calling the API verses db/session lookup).
Note: If you don't have a Google Cloud Platform account, sign up and create a new project. Add the Cloud Translation API to it. You can use Insomnia to test your API key.
📋 Step-by-Step Guide: Getting Your Google Translate API Key
Follow these detailed steps to obtain your Google Translate API key:
Step 1: Create a Google Cloud Account & Project
- Visit Google Cloud Console: Go to https://console.cloud.google.com/
- Sign In/Register: Sign in with your Google account or create a new one
- Accept Terms: Accept the Google Cloud Platform Terms of Service
- Create New Project:
- Click on the project dropdown (top-left, next to "Google Cloud Platform")
- Click "New Project"
- Enter a project name (e.g., "My Translation App")
- Click "Create" and wait for the project to be created
- Select your new project from the project dropdown
Step 2: Enable Billing (Required)
- Go to Billing: In the left sidebar, click "Billing" or visit https://console.cloud.google.com/billing
- Link Billing Account:
- If you don't have a billing account, click "Create Account" and follow the setup
- Add a valid credit card (Google offers $300 free credits for new accounts)
- Link the billing account to your project
Step 3: Enable the Cloud Translation API
- Go to APIs & Services: In the left sidebar, click "APIs & Services" > "Library"
- Search for Translation API: Search for "Cloud Translation API"
- Enable the API:
- Click on "Cloud Translation API"
- Click the "Enable" button
- Wait for the API to be enabled (may take a few moments)
Step 4: Create API Credentials
- Go to Credentials: In the left sidebar, click "APIs & Services" > "Credentials"
- Create API Key:
- Click "Create Credentials" dropdown
- Select "API key"
- Your new API key will be generated and displayed
- Copy the API key and store it securely
Step 5: Restrict Your API Key (Recommended for Security)
- Edit API Key: Click on the API key you just created to edit it
- Add API Restrictions:
- In the "API restrictions" section, select "Restrict key"
- Check "Cloud Translation API" from the list
- Click "Save"
- Add Application Restrictions (Optional but recommended):
- Choose "HTTP referrers" for web applications
- Add your domain(s), e.g.,
*.yourdomain.com/*
- Or choose "IP addresses" for server applications
- Click "Save"
Step 6: Add API Key to Your Laravel Project
-
Add to .env file: Copy your API key to your Laravel
.env
file: - Clear config cache:
Step 7: Test Your Setup
You can test your API key using a simple curl command:
💡 Important Notes:
- Free Tier: Google offers 500,000 characters per month free
- Billing Required: Even for free tier usage, you must have a valid billing account
- Security: Always restrict your API keys to prevent unauthorized usage
- Rate Limits: Be aware of quota limits and implement proper error handling
- Cost Monitoring: Set up billing alerts to monitor your usage
🔧 Troubleshooting:
- 403 Forbidden: Check if the Cloud Translation API is enabled for your project
- Invalid API Key: Ensure the key is copied correctly and has proper restrictions
- Billing Issues: Verify that billing is enabled and your account is in good standing
- Rate Limits: Implement exponential backoff for handling rate limit errors
Review any configuration file changes that you might want to make. The config file is published to the main config folder.
You're all set! 😉
Restart your service and update your Blade files with the @transl8
directive. Only new untranslated phrases will trigger an API call. Future requests for the same phrase will be retrieved from the database.
HTML Blade Example
Here are a few examples of how to use the translate Blade directive in your HTML (Blade) files:
Blade Directive Example
Four directives are available by default (@transl8()
is the main one). You can add more in your Laravel AppServiceProvider file (under the register()
method).
API Routes for Language Management
The package automatically provides HTTP endpoints for setting and getting the user's preferred language. These routes are enabled by default but can be configured or disabled via the config file.
Available Endpoints
Set Language Preference
Get Current Language Preference
JavaScript Example
Configuration Options
Add these optional environment variables to customize the routes:
Custom Implementation
If you prefer to implement your own routes and controller, you can disable the automatic routes by setting DOM_TRANSLATE_ROUTES_ENABLED=false
in your .env
file and use the helper methods directly:
Auto-Translation with User Language Preferences (@transl8auto
)
The @transl8auto()
directive is the most powerful feature of this package. Unlike the basic @transl8()
directive that requires you to specify the target language, the auto directive automatically translates content based on the user's preferred language stored in their session or cookie.
🚀 Smart Features: When users change their language preference, the package automatically clears view cache to ensure immediate translation updates, and the included SetLocaleMiddleware ensures Laravel's built-in localization (
__()
, validation messages, dates) all use the same language consistently.
Key Features
✅ Automatic Cache Management: View cache is automatically cleared when language changes ✅ Laravel Locale Integration: SetLocaleMiddleware ensures unified language experience ✅ Persistent Preferences: Uses both session and cookies for language persistence ✅ Intelligent Fallbacks: Multiple fallback levels ensure content is always displayed ✅ Performance Optimized: Database caching minimizes API calls ✅ Zero Configuration: Works out of the box with sensible defaults
How Auto-Translation Works
The auto-translation system follows this priority order:
- Session: Checks for the user's language preference in the session
- Cookie: Falls back to a long-term cookie if no session is found
- Config Default: Uses the default destination language from your config file
- App Locale: Falls back to Laravel's app locale
- English: Final fallback to English if nothing else is set
Basic Usage
Complete Implementation Guide
To implement a fully functional language selector with auto-translation, follow these steps:
Step 1: Create a Language Selector Dropdown
Add this language selector to your navigation or header layout:
Step 2: Add JavaScript for Language Selection
Add this JavaScript to handle language switching:
Step 3: Add CSS Styling (Optional)
Style your language selector:
Step 4: Update Your Views with Auto-Translation
Replace your static text with auto-translation directives:
Advanced Configuration
Custom Session/Cookie Key
If you want to use a different session/cookie key name:
Disable Routes (Use Custom Implementation)
If you prefer to create your own language switching endpoints:
Then create your own controller:
Best Practices
- Fallback Strategy: Always ensure English content is available as a fallback
- Performance: The first translation of each phrase will hit the Google API, subsequent requests use the database
- Cache Management: View cache is automatically cleared when language changes - no manual intervention needed
- Middleware Integration: The SetLocaleMiddleware automatically handles Laravel locale setting for consistent experience
- User Experience: Consider showing a loading indicator during language changes
- SEO: For SEO-sensitive applications, consider implementing hreflang tags
- Testing: Test with different language combinations to ensure proper fallbacks
- Language Files: Combine
@transl8auto()
with Laravel's__()
helper for system messages
Troubleshooting Auto-Translation
Problem: Auto-translation not working
- Solution: Check if the session/cookie is being set correctly
- Debug: Use browser dev tools to inspect the network requests
Problem: Translations not persisting between sessions
- Solution: Ensure cookies are being set with proper domain and path settings
Problem: Some phrases not translating
- Solution: Check your Google API quotas and error logs
Problem: View cache not clearing after language change
- Solution: The package automatically clears view cache, but if issues persist, manually run
php artisan view:clear
Problem: Laravel's built-in localization not syncing with translation system
- Solution: Ensure the
SetLocaleMiddleware
is properly registered in your middleware stack
Example: Complete Language Switcher Component
Here's a complete Vue.js component for language switching:
Laravel Locale Integration (SetLocaleMiddleware)
The package includes an automatic Laravel locale middleware that seamlessly integrates with Laravel's built-in localization system. This ensures that both your @transl8auto()
directives AND Laravel's native __()
, trans()
, and validation messages all use the same user-selected language.
How It Works
The SetLocaleMiddleware
automatically:
- Reads User Preference: Gets the user's language preference from session/cookie
- Sets Laravel Locale: Calls
app()->setLocale($language)
on every request - Carbon Integration: Also sets Carbon date localization if available
- Unified Experience: Ensures consistent language across your entire application
Automatic Setup (Default)
By default, the middleware is automatically enabled and applied to all web routes. No configuration needed!
Manual Configuration
If you want to customize the middleware behavior:
Manual Middleware Usage
If you disabled auto-apply, you can manually add the middleware to specific routes:
Benefits of Laravel Locale Integration
Before (without middleware):
After (with middleware):
Creating Language Files
To use Laravel's built-in localization alongside the package, create language files:
Best Practices
- Combine Both Systems: Use
@transl8auto()
for dynamic content and__()
for static/system messages - Language Files: Create Laravel language files for form validation, error messages, etc.
- Fallbacks: Both systems fall back to English if translations aren't available
- Performance: Laravel's
__()
helper uses file-based caching, while@transl8auto()
uses database caching
Example: Complete Multilingual Form
Advanced: Custom Middleware Implementation
If you need custom locale logic, you can create your own middleware:
Future Development (Backlog)
- Translations are not always perfect. Create a Phrase vs Translation admin section that will allow admin users to change (update) a translated phase with corrections.
- Create alternative translation engines. Currently, only Google Translate is supported via
Wazza\DomTranslate\Controllers\ApiTranslate\GoogleTranslate()
. Other options to consider include NLP Translation, Microsoft Translator, etc.
Running Local Tests
Run the following command to execute tests:
Important: For the final two assert tests to work, add your personal Google Translate key as DOM_TRANSLATE_GOOGLE_KEY=xxx
in your .env
file (free options are available at the time of writing), or directly in the phpunit.xml
file under DOM_TRANSLATE_GOOGLE_KEY
.
All versions of dom-translate with dependencies
guzzlehttp/guzzle Version ^7.8
illuminate/support Version ^12.0
php Version ^8.2 || ^8.3