Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here
Courses

Multi-Language Laravel 11: All You Need to Know

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...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 67 courses (1172 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord