Courses

Multi-Language Laravel 11: All You Need to Know

Localizing Dates and Currencies

Summary of this lesson:
- Use Carbon for localizing dates and time differences
- Set locale in AppServiceProvider
- Utilize `isoFormat()` and `diffForHumans()` methods
- Use PHP's NumberFormatter for currency localization
- Create helper functions for currency formatting

Translating all the months and currency names manually yourself would be a lot of work. Luckily, in Laravel we can use PHP packages to help with this!


Localizing Dates

Localizing dates with Carbon is really easy. All you need to do is to set the locale of the Carbon instance to the current locale. This can be done in the AppServiceProvider:

app/Providers/AppServiceProvider.php

use Carbon\Carbon;
 
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// ...
 
Carbon::setLocale(app()->getLocale());
 
//...
}
}

Now, when you use Carbon in your views, it will automatically use the correct locale:

resources/views/welcome.blade.php

{{ now()->isoFormat('dddd, D MMMM YYYY') }}

Which will output:

  • English: Monday, 3 April 2023
  • Spanish: lunes, 3 abril 2023
  • German: Montag, 3 April 2023
  • etc.

It's as easy as that - no need to translate all the months yourself!


Localizing Date Differences

You can also localize the difference between the two dates, in a human-readable format. For example, if you want to show how long ago a post was created, you can use the diffForHumans method:

Controller

$start = now()->subMinutes(56)->subSeconds(33)->subHour();
$end = now();
$difference = $end->longRelativeDiffForHumans($start, 5);
dd($difference);

Which will output...

The full lesson is only for Premium Members.
Want to access all 18 lessons of this course? (80 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord