Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Object Translation Bundle Laravel Package

calamityju/object-translation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require calamityju/object-translation-bundle

Publish the configuration (if needed) and run migrations:

php artisan vendor:publish --provider="CalamityJu\ObjectTranslationBundle\ObjectTranslationServiceProvider"
php artisan migrate

First Use Case: Translate a model attribute dynamically. For example, if you have a Product model with a name field that needs translation support:

use CalamityJu\ObjectTranslationBundle\Traits\Translatable;

class Product extends Model
{
    use Translatable;

    protected $translatable = ['name'];
}

Now you can fetch translations:

$product = Product::find(1);
$englishName = $product->getTranslation('name', 'en');
$spanishName = $product->getTranslation('name', 'es');

Check the documentation for model setup and query builder integration.


Implementation Patterns

Basic Usage

  1. Model Integration:

    • Use the Translatable trait on Eloquent models.
    • Define translatable fields in the $translatable property.
    • Example:
      class Article extends Model
      {
          use Translatable;
      
          protected $translatable = ['title', 'content'];
      }
      
  2. Querying Translations:

    • Fetch translations for a specific locale:
      $article->getTranslation('title', 'fr');
      
    • Get all translations for a model:
      $article->getTranslations('title');
      

Workflows

  • Creating/Updating Translations: Use the setTranslation method:

    $article->setTranslation('title', 'es', 'Título en español');
    $article->save();
    
  • Default Fallback: Configure a default locale in config/object-translation.php (e.g., default_locale = 'en'). Fallback logic is built-in:

    $article->getTranslation('title'); // Uses 'en' if no other locale is specified
    
  • Query Builder: Filter models by translation content:

    $articles = Article::whereTranslation('title', 'like', '%Laravel%')->get();
    

Integration Tips

  • Localization Middleware: Attach translations to requests dynamically:
    public function handle($request, Closure $next)
    {
        app()->setLocale($request->header('Accept-Language'));
        return $next($request);
    }
    
  • API Responses: Serialize translations in JSON responses:
    return response()->json([
        'data' => $article->getTranslations('title')
    ]);
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If you manually created translation tables, ensure they match the bundle’s expected schema (e.g., translatable_{model_name}). Run php artisan vendor:publish --tag=migrations to overwrite if needed.
  2. Locale Handling:

    • The bundle assumes ISO 639-1 locale codes (e.g., en, es). Custom locales may require middleware or config adjustments.
  3. Caching:

    • Translations are not cached by default. For performance, implement a cache layer (e.g., Redis) around getTranslation calls.

Debugging

  • Missing Translations: Verify the $translatable array is correctly defined in your model. Check the database for missing records in the translation table.

  • Query Builder Issues: Ensure the whereTranslation method is used correctly. Example:

    // Correct:
    Article::whereTranslation('title', 'like', '%Test%')->get();
    // Incorrect (will fail):
    Article::where('title', 'like', '%Test%')->get(); // No translation logic
    

Extension Points

  1. Custom Storage: Override the default translation storage (e.g., switch to a NoSQL database) by binding a custom repository:

    $this->app->bind(
        \CalamityJu\ObjectTranslationBundle\Repositories\TranslationRepository::class,
        \App\Repositories\CustomTranslationRepository::class
    );
    
  2. Events: Listen for translation-related events (e.g., translation.created):

    use CalamityJu\ObjectTranslationBundle\Events\TranslationCreated;
    
    TranslationCreated::dispatch($translation);
    
  3. Validation: Extend validation rules for translations:

    use CalamityJu\ObjectTranslationBundle\Rules\TranslationExists;
    
    $request->validate([
        'translation' => ['required', new TranslationExists('articles', 'title')],
    ]);
    
  4. Localization Fallback: Modify the fallback logic in app/Providers/AppServiceProvider:

    public function boot()
    {
        \CalamityJu\ObjectTranslationBundle\ObjectTranslation::setFallbackLocales(['en', 'es']);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums