Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 67 ยท Architecture and Extending

Localization, Time Zones and Multi-Tenancy in Laravel

Translate Laravel apps with lang files and pluralization, switch locales, handle time zones with Carbon, and isolate tenant data with global scopes.

The moment your application has users in more than one country, three problems appear together. The text has to speak their language. The times have to make sense in their part of the world: "your meeting is at 15:00" means nothing without a time zone. And if you serve many customers (companies, schools, shops) from one codebase, each customer must only ever see their own data.

Laravel has a solution for each: localization with language files, Carbon for dates and time zones, and global scopes as a building block for multi-tenancy. In this lesson you will learn the real APIs (shown in read-only blocks, since Laravel cannot run on this site) and run plain-PHP stand-ins for a translator with plurals, time zone conversion and tenant scoping. For PHP's own tools see internationalization and date and time.

Language files

Translations live in the lang folder at the project root, one folder per locale (a new app does not include it; create it with php artisan lang:publish):

TEXT
lang/
  en/
    messages.php
    validation.php
  es/
    messages.php
  fr.json

There are two styles. PHP files return an array and use short keys, which you read as file.key:

PHP
// lang/en/messages.php
return [
    'welcome' => 'Welcome, :name!',
    'apples'  => '{0} No apples|{1} One apple|[2,*] :count apples',
];

// lang/es/messages.php
return [
    'welcome' => 'ยกBienvenido, :name!',
];

JSON files use the full English sentence as the key, handy for small apps and quick translations: lang/fr.json contains {"Welcome back": "Bon retour"}. You read them with the sentence itself.

PHP
echo __('messages.welcome', ['name' => 'Ada']);     // Welcome, Ada!
echo trans('messages.welcome', ['name' => 'Ada']);  // same thing
echo __('Welcome back');                           // JSON key

In Blade you write {{ __('messages.welcome', ['name' => $user->name]) }}, or the @lang('messages.welcome') directive. Placeholders start with a colon, and Laravel keeps the capitalization pattern: a :name value of ada in :NAME becomes ADA, and in :Name becomes Ada. If a key is missing in the current locale, Laravel falls back to the fallback locale and, if that is missing too, shows the key itself, which makes gaps easy to spot.

Pluralization

Plural rules differ by language: English has two forms, Russian has several, Japanese has none. Laravel's trans_choice() selects a form from a string with | separators and fills in :count:

PHP
// 'apples' => 'There is one apple|There are many apples'
trans_choice('messages.apples', 1);    // There is one apple
trans_choice('messages.apples', 5);    // There are many apples

// explicit ranges: {n} an exact count, [a,b] an inclusive range, * is infinity
// 'apples' => '{0} No apples|{1} One apple|[2,*] :count apples'
trans_choice('messages.apples', 0);    // No apples
trans_choice('messages.apples', 12);   // 12 apples

// extra placeholders
trans_choice('messages.minutes_ago', 3, ['value' => 3]);

For languages with more plural forms, you write more | segments and Laravel (through Symfony's translation component) chooses the right one using the locale's rules. Always use trans_choice() for anything with a count. Writing "$n item(s)" is lazy and wrong in many languages.

flowchart LR
    K["__('messages.welcome', ['name' => 'Ada'])"] --> L{"Key in current locale?"}
    L -- "yes" --> R["Replace :name"]
    L -- "no" --> F{"Key in fallback locale?"}
    F -- "yes" --> R
    F -- "no" --> M["Return the key itself"]
    R --> O["Final string"]

A lookup tries the current locale, then the fallback locale, and finally shows the key.

The stand-in below implements this lookup with fallback, placeholders with capitalization and a plural chooser that understands the and [a,*] syntax.

PHP A translator with fallback, placeholders and plurals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Setting and switching the locale

The current locale comes from APP_LOCALE in .env (config key app.locale), and the fallback from APP_FALLBACK_LOCALE. At runtime you change it per request with App::setLocale(). The usual approach for a site with a language switcher is a small middleware that reads the locale from the URL prefix, a user preference or the session, and validates it against a list of allowed values:

PHP
public function handle(Request $request, Closure $next): Response
{
    $locale = $request->route('locale')
        ?? $request->user()?->locale
        ?? $request->session()->get('locale', config('app.locale'));

    if (in_array($locale, ['en', 'es', 'fr'], true)) {
        App::setLocale($locale);
    }

    return $next($request);
}

The allow-list matters: never pass raw user input to setLocale(). Using a URL prefix such as /es/products is the best choice for SEO because each language has its own URL; it works nicely with route groups (route groups). Also remember that the locale is per request: a queued job or notification does not know the visitor's language unless you pass it along (->locale('es') on mailables and notifications does exactly that).

Locale also affects number and date formatting. Carbon can format dates in a language ($date->locale('es')->isoFormat('LL')), and PHP's NumberFormatter (from the intl extension) formats numbers and currencies.

Dates and time zones with Carbon

Laravel dates are Carbon objects: now(), today(), Carbon::parse('2026-03-01') and Eloquent's date casts all return them. Carbon extends PHP's DateTime with friendly methods (addDays(), diffForHumans(), startOfMonth()), and the safe immutable version is CarbonImmutable.

The golden rule for time zones: store UTC, show local.

  • Keep 'timezone' => 'UTC' in config/app.php (the default). Laravel then stores and reads all database timestamps in UTC.
  • Store each user's time zone (for example Europe/Berlin) on their profile.
  • Convert only at the edges, when you display or when you read what the user typed:
PHP
$meeting = Carbon::parse('2026-03-29 15:00', $user->timezone)   // user typed local time
    ->utc();                                                    // store UTC

echo $meeting->copy()->setTimezone('Asia/Tokyo')->format('Y-m-d H:i T');
echo $meeting->timezone($user->timezone)->toDayDateTimeString();

Two traps are worth knowing. Daylight saving time means "same time tomorrow" is not always 24 hours later, so for recurring events store the local time plus the zone name instead of a UTC instant. And store zone names (America/New_York), never fixed offsets (-05:00), because the offset changes during the year. Compare instants with Carbon's isBefore(), isAfter() and diffInMinutes() rather than by string. In tests, freeze the clock with $this->travelTo(...) or Carbon::setTestNow() so results are deterministic (faking and mocking).

The next example uses PHP's own DateTimeImmutable, which Carbon is built on, to show the store-UTC-show-local rule with fixed dates around a daylight-saving change.

PHP Store UTC, show local: time zones and DST

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Multi-tenancy and tenant scoping

Multi-tenancy means one application serves several independent customers (tenants), such as companies in a project-management tool. There are three common designs:

Design How data is separated Trade-off
Single database, tenant column Every tenant-owned table has a tenant_id Simplest and cheapest; isolation depends on your code being correct
Database per tenant Each tenant has its own database Strong isolation and easy per-tenant backup; more operational work
Schema per tenant A schema inside one database Middle ground, mostly with PostgreSQL

For most projects the first is the right start, and Eloquent's global scopes are what make it safe. A global scope is a constraint added to every query of a model automatically, so you cannot forget the where:

PHP
namespace App\Models\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        if ($tenantId = app('currentTenantId')) {
            $builder->where($model->getTable().'.tenant_id', $tenantId);
        }
    }
}

A trait attaches the scope and also fills tenant_id on create, so developers cannot forget either half:

PHP
trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::addGlobalScope(new TenantScope());

        static::creating(function (Model $model) {
            $model->tenant_id ??= app('currentTenantId');
        });
    }
}

class Project extends Model
{
    use BelongsToTenant;
}

A middleware resolves the current tenant from the subdomain (acme.example.com) or the signed-in user and binds it in the container. After that, Project::all() returns only that tenant's projects. Cases to handle with care: jobs and commands (no web request, so pass the tenant id along and set it first), withoutGlobalScopes() (an escape hatch for admin tools; search for it in code review), raw queries and joins that bypass the scope, and unique rules, which must be scoped per tenant (Rule::unique('projects')->where('tenant_id', $tenantId)). Write tests that prove tenant A cannot read tenant B's records. Packages such as Spatie's laravel-multitenancy and Tenancy for Laravel solve database-per-tenant setups when you need them.

The stand-in below shows the same idea with SQLite: a query helper that always adds the tenant condition, an automatic tenant_id on insert, and an unscoped escape hatch.

PHP Tenant scoping with a global scope on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does trans_choice('messages.apples', 5) do?

    trans_choice reads a string with several forms separated by |, selects the one for the count, and fills :count. This handles languages with different plural rules.
  2. 2. What is the recommended practice for storing times in a multi-timezone app?

    UTC is unambiguous. Convert at the edges, using time zone names such as Europe/Berlin, not fixed offsets, because offsets change with daylight saving time.
  3. 3. What happens when a translation key is missing in both the current and fallback locales?

    The key is shown as is, which makes a missing translation visible during development.
  4. 4. Why is a global scope a good fit for single-database multi-tenancy?

    A global scope removes the risk of forgetting a where tenant_id clause. You still have to watch raw queries, jobs and withoutGlobalScopes calls.
  5. 5. Why must the locale be validated against an allow-list before calling App::setLocale()?

    A locale from a URL or cookie is user input. Checking it against the languages you actually support keeps lookups predictable.

Summary

  • Translations live in lang/<locale>/file.php (short keys) or lang/<locale>.json (sentence keys), read with __(), trans() and @lang.
  • Placeholders start with a colon, trans_choice() handles plurals, and a missing key falls back to the fallback locale and then to the key itself.
  • Switch the locale per request with App::setLocale() from a middleware and an allow-list; pass the locale to jobs and notifications explicitly.
  • Store UTC, keep zone names on user profiles, convert at display time, and beware of daylight saving.
  • For tenants sharing one database, a global scope plus a trait that fills tenant_id keeps queries isolated; test that tenants cannot see each other's data.

Next: Project: A Blog with Authentication