Cours Laravel 10 – la localisation (2023)

Lorsqu’on crée un site c’est souvent dans une optique multi-langages. On parle alors d’internationalisation (i18n) et de localisation (L10n). L’internationalisation consiste à préparer une application pour la rendre potentiellement adaptée à différents langages. La localisation consiste quant à elle à ajouter un composant spécifique à une langue.

C’est un sujet assez complexe qui ne se limite pas à la traduction des textes mais qui impacte aussi la représentation des dates, la gestion des pluriels, parfois la mise en page…

Qu’a à nous proposer Laravel dans ce domaine ? Nous allons le voir dans ce chapitre.

Pour les curieux i18n parce qu’il y a 18 lettres entre le «i» et le «n» de internationalisation et L10n parce qu’il y a 10 lettres entre le «L» et le «n» de Localisation.

Le principe

Les fichiers de langage

On a deux façons de gérer les langues.

Clés et valeurs

On a déjà parlé des fichiers de langage. Lorsque Laravel est installé, il n’y a aucune information concernant le langage dans l’application. Mais on peut utiliser cette commande d’artisan pour les publier :

php artisan lang:publish

On a cette architecture :

Il n’est prévu au départ que la langue anglaise (en) avec 4 fichiers. Pour ajouter une langue, il suffit de créer un nouveau dossier, par exemple frpour le Français.

Il faut évidemment avoir le même contenu comme nous allons le voir.

Vous n’allez pas être obligé de faire toute cette traduction vous-même ! Certains s’en sont déjà chargés avec ce package. Nous l’avons déjà utilisé dans ce cours.

On va ajouter la traduction française :

composer require laravel-lang/common --devphp artisan lang:add frphp artisan lang:update

(Video) Laravel 10 full course for beginner - Understand the migrations

Les fichiers présents sont constitués de la même manière. Prenons le plus léger : pagination.php, pour l’anglais, on a :

return [ 'previous' => '« Previous', 'next' => 'Next »',];

On voit qu’on se contente de renvoyer un tableau avec des clés et des valeurs. On ne peut pas faire plus simple ! Si on prend le même fichier en version française :

return [ 'previous' => '« Précédent', 'next' => 'Suivant »',];

On retrouve bien sûr les mêmes clés avec des valeurs adaptées au langage.

Les textes

Le système clé/valeur peut devenir rapidement lourd et confus lorsqu’on a beaucoup de textes à traduire. Laravel propose une autre approche qui consiste à utiliser la traduction par défaut comme clé.

Si la langue par défaut est l’anglais par exemple, on aura le texte anglais directement dans le code. Les autres traductions se trouveront dans des fichiers JSON.

Par exemple, pour le français, on a le fichier fr.json :

Ce fichier contient des éléments de ce type :

"90Days":"90jours",

On a :

  • 90Days : le texte en langage par défaut présent dans le code
  • 90 jours : la traduction en français

Les deux systèmes peuvent cohabiter et se compléter.

Configuration de la locale

La configuration de la locale est effectuée dans le fichier config/app.php :

'locale' => 'en',

On peut changer cette locale en cours d’exécution si nécessaire :

App::setLocale('fr');

Si une traduction n’est pas trouvée dans la locale actuelle, alors on va chercher la traduction de la locale par défaut définie également dans le fichier config/app.php :

(Video) Laravel 10 full course for beginner - form request data

'fallback_locale' => 'en',

On peut connaître la locale actuelle :

$locale = App::getLocale();

Et même tester si on a une certaine locale :

if (App::isLocale('fr')) { //}

Dans le code

L’helper __

Concrètement, au niveau du code, on utilise l’helper __. Il suffit de préciser la clé comme paramètre (la clé pour le système clé-valeur et le texte dans la langue d’origine pour le second système). Prenons un exemple :

$info = __('Posts for category: ');

Si la locale est en c’est ce texte qui sera directement affiché. Si la locale est fr c’est le texte correspondant qu’on trouve dans le fichier fr.json qui sera affiché :

"Posts for category: ": "Articles pour la catégorie : ",

Blade

On peut utiliser l’helper __ dans une vue Blade :

{{ __('Get In Touch With Us') }}

Mais il est plus pratique d’utiliser la directive @lang :

@lang('Get In Touch With Us')

Le pluriel

La gestion du pluriel n’est pas toujours facile. On peut prévoir le texte du singulier et celui du pluriel séparés par le caractère | :

'pommes' => 'une pomme|plusieurs pommes',

On peut affiner :

'pommes' => '{0} aucune pomme|[1,10] quelques pommes|[10,*] beaucoup de pommes',

On utilise dans le code la fonction trans_choice. Voici un exemple tiré d’une application :

{{ trans_choice(__('comment|comments'), $post->valid_comments_count) }}

Selon la valeur de $post->valid_comments_count, autrement dit le nombre de commentaires valides, on prend le singulier ou le pluriel grâce à trans_choice et dans la langue voulue grâce à l’helper __.

Si on a un seul commentaire, on a le singulier :

Sinon on a le pluriel :

(Video) Laravel 8 tutorial - Localization | locale

Des assistants

Pour gérer toutes ces traductions, il existe des assistants bien utiles.

Pour le système clé-valeur voici un package intéressant :

Cours Laravel 10 – la localisation (6)

Il copie les fichiers de langue dans la base de données et permet une gestion à partir d’une interface web.

Pour la gestion des fichiers JSON j’ai aussi créé un package :

Il ajoute 4 commandes à Artisan :

  • language:strings pour visualiser tous les textes du code (dans app et resource/views)
  • language:make pour créer un fichier JSON pour une locale complétée avec les textes du code
  • language:diff pour voir les différences entre une locale JSON et les textes du code
  • language:sync pour synchroniser une locale JSON avec les textes du code

Les noms pour la validation

Il y a un autre élément à prendre en compte pour la traduction : le nom des contrôles de saisie. Ces noms ne sont pas visibles tant qu’il n’y a pas de souci de validation, ils sont alors transmis dans le texte de l’erreur.

‌On voit mal présenter en langue française « Le champ name est obligatoire… ». Alors comment faire ?

Si vous regardez dans le fichier resources/lang/fr/validation.php vous trouvez ce tableau :

'attributes' => [ 'address' => 'adresse', 'age' => 'âge'

Ici, on fait correspondre le nom d’un attribut avec sa version linguistique pour justement avoir quelque chose de cohérent au niveau du message d’erreur.

Les dates

Il ne vous a sans doute pas échappé que les dates et les heures ne sont pas présentées de la même manière selon la langue utilisée. En particulier entre le français et l’anglais.

(Video) #10 Localization | Laravel Telugu Tutorials

En France nous utilisons le format jj/mm/aaaaalors que les Américainsutilisent le format mm/jj/aaaa. De la même façon les heures sont présentées différemment.

Laravel utilise Carbon pour la gestion des dates. Carbon hérite de la classe PHP DateTime. On dispose donc de toutes les possibilités de cette classe, plus toutes celles ajoutées par Carbon, et elles sont nombreuses. Le vous conseille vivement la lecture de la documentation.

Quand Eloquent récupère une date de created_at ou updated_at il la transforme automatiquement en instance Carbon. On peut modifier ce comportement, mais je n’en vois pas l’intérêt sauf cas bien particulier.

Partez d’une nouvelle installation de Laravel et allez dans le fichier AppServiceProvider pour ajouter ce code :

public function boot(): void{ setlocale(LC_TIME, config('app.locale')); ...}

La méthode setLocale fait appel à la fonction PHP strftime. C’est ainsi qu’on a la date et l’heure bien affichées pour l’anglais et le français.

Dans la vue welcome.blade.php entrez ce code :

Date : {{ \Carbon\Carbon::now()->isoFormat('LL') }}

En anglais, vous affichez :

Date : October1,2020

Et en français :

Date : 1octobre2020

Dans la vue welcome.blade.php entrez maintenant ce code :

Date : {{ \Carbon\Carbon::now()->calendar() }}

En anglais, vous affichez :

Date : Todayat12:27PM

Et en français :

Date : Aujourd’huià12:27

Le but de ce chapitre est de montrer comment localiser l’interface d’une page web. S’il s’agit d’adapter le contenu selon la langue, c’est une autre histoire et il faut alors intervenir au niveau de l’url. En effet, un principe fondamental du web veut que pour une certaine url on renvoie toujours le même contenu.

En résumé

  • Laravel possède les outils de base pour la localisation.
  • Laravel propose deux systèmes complémentaires : clé-valeur ou texte dans le code associé à des fichiers JSON.
  • Il faut créer autant de fichiers de localisation qu’on a de langues à traiter.
  • Il faut prévoir la version linguistique des attributs.
  • Grâce à Carbon la présentation des dates est heures selon la locale est simplifiée.

(Video) Laravel 10 full course for beginner - How register form works

FAQs

What are the requirements for Laravel 10x? ›

Laravel 10.x requires a minimum PHP version of 8.1.

What is the minimum requirement for Laravel 10? ›

Laravel 10 drops support for PHP 8.0

0 in Laravel 10. The minimum required version is PHP ^8.1 . Browsing the comparison between master and 9. x, we can expect to see 8.1 features used in the framework, such as readonly properties.

Is Django better than Laravel? ›

Django comes out on top in terms of speed (thanks in part to the faster Python), scalability and maintenance. Its built-in tools include decorators, SEO tools and third-party libraries. Laravel, on the other hand, is easier to use thanks to its simpler features, and contains strategy infusion as well.

Why is Laravel easy? ›

Laravel is responsive and straightforward to use. Laravel provides developers with an inbuilt library of tools that reduce the amount of coding they need to do. Laravel is easy to learn. Laravel allows the developer to focus on their web application's design, architecture, and functionality.

How do I get the highest salary in Laravel? ›

The top 5 highest paying jobs who knows Laravel with reported salaries are: software developer - ₹29.0lakhs per year. head of technology - ₹25.0lakhs per year. technical project manager - ₹20.0lakhs per year.

How to pass Laravel certification exam? ›

Laravel Exam Preparation

The prerequisites are; practicing documentation and hands-on experience in projects. Otherwise, a small workout on the concepts while reading the documentation should help in logical thinking and answering logic-type questions.

Is Laravel 10 stable? ›

In short, you should consider upgrading to Laravel 10 when: The application is stable with its current version and functioning without problems. The new version either adds a feature that your application requires or fixes an issue that your application is experiencing.

Is 1gb RAM enough for Laravel? ›

You can run Laravel in production with thousands of users on 2GB RAM.

How much time is required to learn Laravel? ›

How long does it take to learn Laravel? Learning Laravel can take up to six months. If you're experienced with PHP, it could take as little as three weeks. Laravel's official documentation strongly advises learning HTML, Core PHP, and Advanced PHP to get the most out of this framework.

Is Laravel worth learning 2023? ›

It's a good choice for web development in 2023 because of its elegant syntax, built-in support for MVC architecture, routing, query builder, ORM system, authentication and authorization, task scheduler, active community, ability to handle complex web applications, localization, and event handling.

Do people still use Laravel? ›

Yes, Laravel is still relevant in 2022. The number of websites using Laravel is increasing. Many web and mobile app developers rely on Laravel to build small and medium-scale websites and web-based mobile apps.

Is Laravel in demand? ›

And Laravel is one such PHP-based open-source web application framework that is used to develop scalable, robust, and highly-functional web applications. For brands, the craze of opting for Laravel application development is increasing day by day.

Is Laravel a skill? ›

Database Management Skills

Laravel developers are experts in managing database systems. They can organize all the data from a company's website, making it easier for end-users to quickly and effectively share the data across the organization.

What is the weakness of Laravel? ›

The framework's strong points include high security, robust deployments, and simple coding. It also boasts a variety of web development tools and is easy to learn. The drawbacks include the potentially high cost of Laravel developers, limited support, frequent need for updates, and slow speeds.

Why is Laravel so complicated? ›

Laravel is complicated because it's meant to make a large portion of PHP development simpler for programmers. It covered features used in different settings, starting from testing and seeding to restoring and deployment.

What is the average salary of Laravel in USA? ›

The average Laravel developer salary in the United States of America is $117,386 and can vary anywhere between $78k-$180k/yr.

Can Laravel handle millions of users? ›

We handle millions of users daily and we're not even close to the threshold. I suppose it's a case of: 99.999% of web applications can scale using Laravel but there'll be exceptions. People often forgets its just a framework. Any language/framework can scale.

What is the salary of 1 year Laravel Developer? ›

Laravel Developer salary in India ranges between ₹ 1.0 Lakhs to ₹ 6.6 Lakhs with an average annual salary of ₹ 3.0 Lakhs.

Is Laravel easier to learn than React? ›

Laravel has a steeper learning curve compared to React as it is a full-stack framework that requires knowledge of PHP, HTML, CSS, and JavaScript. On the other hand, React has a relatively shallow learning curve, especially for developers who are already familiar with JavaScript.

How to speed up Laravel tests? ›

Laravel uses the bcrypt password hashing algorithm by default, which is by design slow and expensive on system resources. If your tests verify user passwords, you could potentially trim more time off your test run by setting the number of rounds the algorithm uses, as the more rounds it performs, the longer it takes.

Does Laravel have a future? ›

There are currently 140,886 websites using Laravel and that number is growing all the time. The framework has experienced a noticeable expansion in recent years and will certainly continue to do so in the future.

How to get first 10 rows in Laravel? ›

First you can use a Paginator. This is as simple as: $allUsers = User::paginate(15); $someUsers = User::where('votes', '>', 100)->paginate(15); The variables will contain an instance of Paginator class.

Which Laravel is best? ›

Eloquent ORM

Laravel has the best Object-relational Mapper as compared to the other frameworks out there. This Object-relational mapping allows you to interact with your database objects and database relationships using expressive syntax.

Can Laravel handle big data? ›

Laravel supports Eloquent, which is one of PHP's robust frameworks for data handling, gives you faster access to the data. Laravel contains lighter templates and widgets such as JS and CSS code that are actively being used to manage Big Data.

How much PHP is required for Laravel? ›

The Laravel framework has a few system requirements: PHP >= 5.4, PHP < 7.

Which Laravel version is best for beginners? ›

It's version 5.4, by far the best resource you'll find for laravel.

Is Laravel easier than node JS? ›

Learning Curve

Besides, Laravel becomes easy to implement or execute for developers as it comes with built-in libraries and templates. However, becoming an expert in Laravel needs more effort. For Node JS, developers with relevant Javascript experience can easily learn this framework.

Why Laravel is better than Python? ›

"Clean architecture", "Growing community" and "Composer friendly" are the key factors why developers consider Laravel; whereas "Great libraries", "Readable code" and "Beautiful code" are the primary reasons why Python is favored.

Can I learn PHP in a week? ›

If you're a developer, and you took the time to learn the concepts, you can learn PHP in a few weeks. If you have any experience in Java, the syntax is nearly identical. There aren't any crazy concepts that are so far out of the norm that will take you much longer than a few weeks to grasp.

Is asp net better than Laravel? ›

Which is better: Laravel or ASP Net? Laravel is ideal for building smaller projects, whereas ASP Net is best for medium to large projects that don't need additional support. Laravel projects demand such help, which is not readily available, whereas ASP.net is scalable to cover all huge project metrics.

Is Laravel good for job? ›

Laravel is a popular PHP web framework with millions of websites realizing its potential. It is an ideal, feature-rich framework for the fast creation and implementation of projects. Laravel has been a developer's favorite with its salient features; hence Laravel developers have been in great demand for a long time.

Does Laravel make PHP easier? ›

It's very easy for PHP developers to get started on Laravel because PHP itself is such a familiar code and as such online businesses can save time and budget and benefit from better code by choosing Laravel for their server-side build.

Does Google use Laravel? ›

Introduction. In addition to typical, form based authentication, Laravel also provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite. Socialite currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket.

Is Laravel better than WordPress? ›

Laravel is more developer-oriented. WordPress is a widely used platform, so it's often targeted by hackers, making it more vulnerable to attacks. Laravel comes with built-in security features that are unmatched. The WooCommerce plugin let's you create an online store with ease.

Why not to choose Laravel? ›

Since Laravel is a PHP framework, if you are not building your application in PHP, Laravel is not even a choice. Depending on your chosen programming language, there are other options. For example, if you are going with java there's Spring Framework, for python there's Django and for C# there's . NET Framework.

What is the salary of Laravel developers? ›

Php and Laravel Developer salary in India ranges between ₹ 1.0 Lakhs to ₹ 7.0 Lakhs with an average annual salary of ₹ 3.0 Lakhs. Salary estimates are based on 471 latest salaries received from Php and Laravel Developers.

How much does a senior Laravel developer make in the US? ›

Senior Laravel Developer Salary
Annual SalaryHourly Wage
Top Earners$143,500$69
75th Percentile$131,750$63
Average$107,812$52
25th Percentile$85,000$41

What is the salary of senior Laravel developer? ›

The average senior laravel developer salary in India is ₹ 1,065,000 per year or ₹ 427 per hour.

Is it hard to learn Laravel? ›

If you're sharp-minded and understood the logic fast, then it will be easy for you to learn Laravel. Some people are just natural when it comes to programming. If you're like me and had a hard time understanding PHP/PHP OOP. I'm not a natural, so I had to work harder and more.

Which is better Java or Laravel? ›

Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!. On the other hand, Laravel is detailed as "A PHP Framework For Web Artisans". Laravel is a web application framework with expressive, elegant syntax.

Why do people love Laravel? ›

Laravel offers developers with ease and flexibility to code and build dynamic web solutions like from small-scale business websites to full-scale enterprise applications. Additionally, Laravel simplifies the complete development process thoroughly with clean & reusable code.

Is Laravel low code? ›

Laravel is a great low-code platform or framework for PHP coding! Laravel creates a lot of code automatically and includes a bevy of convenient templates to speed up development.

Can Laravel website be hacked? ›

Laravel hacking is a common problem that can further cause vulnerabilities to other supporting XSS and different files. Most casualties of website hacks find that their site pages are diverted to other malicious websites.

Why Laravel is better than Node JS? ›

Laravel is most suitable for education, business, and shopping. The Nodejs framework has no in-built templates, yet there is a chance to combine third-party tools to fix the problems. The Laravel framework has in-built templates that are designed to develop a basic layout with significant segments for every purpose.

What is the future of Laravel in 2023? ›

Conclusion. The future of Laravel development in 2023 looks promising, with increased adoption of Laravel-based CMS platforms, the emergence of new development tools and libraries, increased focus on security and performance, and the integration of AI and machine learning.

Is Laravel easier than Spring Boot? ›

Learning Curve: Laravel emphasizes developer-friendly syntax and conventions, making it relatively easier for beginners to grasp. It provides a straightforward and intuitive API for common tasks. Spring Boot, while powerful, has a steeper learning curve due to its extensive features and configuration options.

Is PHP Laravel worth learning? ›

As we mentioned above, Laravel is great for database migrations as it uses object-relational mapping (ORM) which supports the most used databases. I've got to say whilst other frameworks have ORMs, the ease of use here is phenomenal.

What are the basic requirements to run Laravel project? ›

The Laravel framework has a few system requirements:
  • PHP >= 5.4, PHP < 7.
  • Mcrypt PHP Extension.
  • OpenSSL PHP Extension.
  • Mbstring PHP Extension.
  • Tokenizer PHP Extension.

What are the basic requirement of Laravel? ›

Laravel - Installation

PHP having version 7.0 or upper version. An OpenSSL extension for PHP. A PDO extension for PHP. Mbstring extension for PHP.

What is needed to run Laravel project? ›

So, before using Laravel, make sure you have Composer installed on your machine.
  1. Via Laravel Installer. First, download the Laravel installer using Composer: ...
  2. Via Composer Create-Project. ...
  3. Local Development Server. ...
  4. Public Directory. ...
  5. Configuration Files. ...
  6. Directory Permissions. ...
  7. Application Key. ...
  8. Additional Configuration.

What are the requirements to learn Laravel? ›

However, here we are providing a general overview of the common Laravel developer skills required for your reference.
  • Knowledge of programming languages. ...
  • Knowledge of MVC and OOP. ...
  • Skilled in DBMS. ...
  • Experience with project management frameworks. ...
  • Knowledge of the latest updates. ...
  • Knowledge of cloud computing and APIs. ...
  • Soft skills.

What is the minimum RAM for Laravel? ›

RAM= 150 people? Minimum 10gb.

Does Laravel require coding? ›

Step 1: Become Familiar With HTML, Core PHP, and Advanced PHP. Laravel is a PHP framework, and all coding is done using PHP language. You have to know how to code in PHP in order to learn Laravel. Because PHP is often used with HTML, you also need to learn basic concepts in HTML.

Can I start Laravel without PHP? ›

You can learn other frameworks where programming languages are not needed. However, to use Laravel effectively, you need to start learning PHP.

How much do Laravel developers make? ›

Php and Laravel Developer salary in India ranges between ₹ 1.0 Lakhs to ₹ 7.0 Lakhs with an average annual salary of ₹ 3.0 Lakhs. Salary estimates are based on 471 latest salaries received from Php and Laravel Developers.

Is Laravel easy or hard? ›

Laravel is amongst the best web development frameworks that can make your website development work so much easy. It takes a lot of time to write code from scratch. Hence, when you're using Laravel, you can save a lot of time because you can reuse code written by great programmers.

How to run Laravel project step by step? ›

The First Steps
  1. mkdir ~/Sites. cd ~/Sites.
  2. # Via the installer. laravel new links. # Via composer. ...
  3. DB_CONNECTION=mysql. DB_HOST=127.0.0.1. DB_PORT=3306. ...
  4. # Connect via the mysql CLI. mysql -u root -p. ...
  5. DB_CONNECTION=mysql. DB_HOST=127.0.0.1. ...
  6. php artisan migrate.
  7. composer install laravel/ui.
  8. php artisan ui bootstrap --auth.
Mar 5, 2021

Is Laravel used for big projects? ›

It works best for large-scale projects. There are many examples that Laravel web development works best for all types of the software framework.

How to make Laravel project faster? ›

Tips to Improve Laravel Performance
  1. Config caching.
  2. Routes caching.
  3. Remove Unused Service.
  4. Classmap optimization.
  5. Optimize Composer.
  6. Limit Use Of Plugins.
  7. JIT Compiler.
  8. Choose a faster cache and session driver.
Jan 3, 2023

Videos

1. Laravel From Scratch 2022 | 4+ Hour Course
(Traversy Media)
2. Laravel 10 Blog with Filament Admin Panel | Part 1
(The Codeholic)
3. Advanced Laravel | Localization - Introduction #10
(Bitfumes)
4. Database Configuration and Migration in Laravel 8 | Laravel Tutorial #10
(WsCube Tech)
5. Laravel 10 full course for beginner - controller and redirect session
(Bitfumes)
6. Découverte de Laravel 10 : TP : Agence immo, gestion des biens
(Grafikart.fr)

References

Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated: 08/05/2023

Views: 6077

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.