PHP code example of upon / mlang

1. Go to this page and download the library: Download upon/mlang library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

upon / mlang example snippets


// Find all products with "laptop" in the name - in ANY language
Product::where('name', 'like', '%laptop%')->get();

// Works with standard Laravel queries, indexes, and full-text search!

// Add to your model
use Upon\Mlang\Contracts\MlangContractInterface;
use Upon\Mlang\Models\Traits\MlangTrait;

class Product extends Model implements MlangContractInterface
{
    use MlangTrait;
}

// Create product in multiple languages at once
MLang::forModel(Product::class)->createMultiLanguage(
    attributes: ['price' => 99.99],
    languages: ['en', 'fr', 'de'],
    translatedAttributes: [
        'en' => ['name' => 'Laptop', 'description' => 'Powerful laptop'],
        'fr' => ['name' => 'Ordinateur', 'description' => 'Ordinateur puissant'],
        'de' => ['name' => 'Laptop', 'description' => 'Leistungsstarker Laptop'],
    ]
);

// Query in current language - automatically filtered!
$products = Product::trWhere('status', 'active')->get();

// config/mlang.php
'models' => [
    \App\Models\Category::class,
    \App\Models\Product::class,
]

use Upon\Mlang\Contracts\MlangContractInterface;
use Upon\Mlang\Models\Traits\MlangTrait;

class Product extends Model implements MlangContractInterface
{
    use MlangTrait;
}

use Upon\Mlang\Facades\MLang;
use App\Models\Category;

// Specify which model to work with
MLang::forModel(Category::class)->migrate();

// Chain multiple operations together
MLang::forModel(Category::class)
    ->migrate()
    ->generate();

// Get model information
$modelName = MLang::forModel(Category::class)->getModelName(); // Returns "Category"
$tableName = MLang::forModel(Category::class)->getTableName(); // Returns the table name

// You can also use a model instance
$category = new Category();
MLang::forModel($category)->generate();

use Upon\Mlang\Facades\MLang;
use App\Models\Product;

// Create product in all configured languages
$records = MLang::forModel(Product::class)->createMultiLanguage([
    'name' => 'Product Name',
    'description' => 'Product Description',
    'price' => 99.99
]);

// Create product in specific languages only
$records = MLang::forModel(Product::class)->createMultiLanguage(
    attributes: [
        'name' => 'Product Name',
        'price' => 99.99
    ],
    languages: ['en', 'fr', 'de']
);

// Create with language-specific content
$records = MLang::forModel(Product::class)->createMultiLanguage(
    attributes: [
        'price' => 99.99,
        'status' => 'active'
    ],
    languages: ['en', 'fr'],
    translatedAttributes: [
        'en' => [
            'name' => 'English Product Name',
            'description' => 'English Description'
        ],
        'fr' => [
            'name' => 'Nom du Produit Français',
            'description' => 'Description Française'
        ]
    ]
);

use Upon\Mlang\Facades\MLang;
use App\Models\Category;

// Get translation statistics
$stats = MLang::forModel(Category::class)->getStats();
// Returns:
// [
//     'total_records' => 150,
//     'unique_records' => 50,
//     'languages' => [
//         'en' => 50,
//         'fr' => 48,
//         'de' => 45
//     ]
// ]

// Get translation coverage percentage
$coverage = MLang::forModel(Category::class)->getCoverage(); // Returns: 94.67

// Get records with incomplete translations
$incomplete = MLang::forModel(Category::class)->getIncompleteTranslations();

use Upon\Mlang\Facades\MLang;
use App\Models\Product;

// Get all translations for a specific product (pass the regular ID)
$productId = 1;
$translations = MLang::forModel(Product::class)->getAllTranslations($productId);
// Returns collection of all language versions (English, French, German, etc.)

// Update all translations at once (common fields like price, status)
$updated = MLang::forModel(Product::class)->updateAllTranslations($productId, [
    'price' => 149.99,
    'status' => 'sale'
]);
// Updates the price and status for all language versions

// Delete all translations for a record (all languages)
$deleted = MLang::forModel(Product::class)->deleteAllTranslations($productId);

// Copy a record to another language - multiple ways:
// 1. Using model instance
$product = Product::find(1);
$frenchProduct = MLang::forModel(Product::class)->copyToLanguage($product, 'fr', [
    'name' => 'Nom du Produit Français'
]);

// 2. Using just the ID (much easier!)
$frenchProduct = MLang::forModel(Product::class)->copyToLanguage(1, 'fr', [
    'name' => 'Nom du Produit Français',
    'description' => 'Description en Français'
]);

// config/mlang.php

// Control automatic generation of translations
'auto_generate' => false,

// Enable automatic migration after Laravel migrations
'auto_migrate' => false,

// Control observer behavior during console operations
'observe_during_console' => false,

// Auto-generate translations after seeding
'auto_generate_after_seed' => false,

// Specify which models to process after migrations/seeding
'auto_generate_models' => 'all',

// Control rollback behavior
'auto_rollback' => true,

// Toggle debug output
'debug_output' => true,

use Upon\Mlang\Facades\Mlang;
use App\Models\Category;

// Generate translations for a specific model
Mlang::forModel(Category::class)->generate();

// Generate translations for a specific model and language
Mlang::generate('Category', 'fr');

// Run migrations for a specific model
Mlang::forModel(Category::class)->migrate();

// Roll back migrations for a specific model
Mlang::forModel(Category::class)->rollback();

protected $middlewareGroups = [
    'web' => [
        // ...
        \Upon\Mlang\Middleware\DetectUserLanguageMiddleware::class,
    ],
    // ...
];

app()->setLocale('fr');

// Find by row_id in current language
$category = Category::trFind(1);

// Find in specific language
$category = Category::trFind(1, 'fr');

// Query in current language
$categories = Category::trWhere(['name' => 'test'])->get();

// Chain other query methods
$categories = Category::trWhere('status', 'active')
                     ->orderBy('created_at', 'desc')
                     ->paginate(10);

// Complex queries
$categories = Category::trWhere(function($query) {
                         $query->where('price', '>', 100)
                               ->orWhere('featured', true);
                     })->get();

// routes/web.php
Route::get('/categories/{category}', function (Category $category) {
    // $category will be automatically fetched in the current application language
    return view('categories.show', compact('category'));
});

class Category extends Model implements MlangContractInterface
{
    use MlangTrait;
    
    // Your model code...
}

use Upon\Mlang\Helpers\SecurityHelper;

// Validate inputs
SecurityHelper::validateLocale('en');
SecurityHelper::validateTableName('users');
SecurityHelper::validateModelClass(Product::class);

// Check database structure
if (SecurityHelper::tableExists('categories')) {
    if (SecurityHelper::columnExists('categories', 'row_id')) {
        // Proceed with operation
    }
}

// Sanitize user inputs
$clean = SecurityHelper::sanitizeValue($userInput);
$cleanAttributes = SecurityHelper::sanitizeAttributes($request->all());

// Rate limiting
if (SecurityHelper::checkRateLimit('bulk_operation', 100, 1)) {
    // Proceed with bulk operation
}

use Upon\Mlang\Helpers\LanguageHelper;

// Get language configuration
$languages = LanguageHelper::getConfiguredLanguages(); // ['en', 'fr', 'de']
$fallback = LanguageHelper::getFallbackLanguage(); // 'en'
$current = LanguageHelper::getCurrentLocale(); // Current app locale

// Check configuration
if (LanguageHelper::isLanguageConfigured('fr')) {
    // French is configured
}

// Parse browser language
$locale = LanguageHelper::parseAcceptLanguageHeader('fr-FR,fr;q=0.9,en;q=0.8');

// Get missing translations
$missing = LanguageHelper::getMissingLanguages(['en', 'fr']); // ['de']

// Get language name
$name = LanguageHelper::getLanguageName('fr'); // 'French'

use Upon\Mlang\Helpers\TranslationHelper;

// Get existing translations
$existing = TranslationHelper::getExistingTranslations($model, $rowId);
// Returns: ['en', 'fr'] if those exist

// Create multi-language records
$records = TranslationHelper::createMultiLanguageRecord(
    $model,
    ['name' => 'Product', 'price' => 99.99],
    ['en', 'fr', 'de']
);

// Copy to another language
$newRecord = TranslationHelper::copyToLanguage($product, 'fr', [
    'name' => 'Nom Français'
]);

// Bulk operations
$count = TranslationHelper::updateAllTranslations($model, $rowId, ['price' => 149.99]);
$deleted = TranslationHelper::deleteAllTranslations($model, $rowId);

// Get statistics
$stats = TranslationHelper::getTranslationStats($model);
// Returns: ['total_records' => 150, 'unique_records' => 50, 'languages' => [...]]

use Upon\Mlang\Helpers\QueryHelper;

// Apply filters to query
$query = Product::query();
QueryHelper::applyLanguageFilter($query, 'fr');
QueryHelper::applyRowIdFilter($query, 123);
$products = $query->get();

// Find specific translation
$product = QueryHelper::findByRowIdAndLocale($model, $rowId, 'fr');

// Get all translations for a record
$translations = QueryHelper::getAllTranslations($model, $rowId);

// Get incomplete translations
$incomplete = QueryHelper::getRecordsWithIncompleteTranslations($model);

// Build MLang-aware query
$query = QueryHelper::buildMlangQuery($model, ['status' => 'active'], 'fr');

// Get coverage percentage
$coverage = QueryHelper::getTranslationCoverage($model); // e.g., 94.67

// ✅ GOOD: Using facade methods (automatically validated)
MLang::forModel(Category::class)->migrate();

// ✅ GOOD: Validated locale
MLang::forModel(Product::class)->generate(locale: 'fr');

// ❌ BAD: Don't use raw SQL with MLang operations
DB::raw("..."); // Not recommended with user input

// ✅ GOOD: Use sanitization for user inputs
$attributes = SecurityHelper::sanitizeAttributes($request->all());
MLang::forModel(Product::class)->createMultiLanguage($attributes);
bash
composer vendor:publish --tag="mlang"
php artisan mlang:migrate
bash
php artisan mlang:migrate
bash
php artisan mlang:generate
bash
php artisan mlang:generate {model}
# Example: php artisan mlang:generate Category
# Or for nested models: php artisan mlang:generate Shop\\Product
bash
php artisan mlang:generate {model|all} {locale}
# Example: php artisan mlang:generate all fr
bash
php artisan mlang:remove {table} {locale}
# Example: php artisan mlang:remove categories fr