Laravel

Must-Read for Laravel Beginners! Simple Guide to Localize Error Messages Using validation.php

In web development, user interface plays a crucial role. Especially, error messages are important sources of information for users. In Laravel, error messages are displayed using the database table column names by default. However, changing them to more user-friendly names in Japanese can greatly improve user experience.

Basics of Laravel and Validation

Laravel is a PHP framework that follows the MVC architecture. Validation is essential to maintain data integrity. Here, we explain the basic concepts of validation in Laravel and why it’s important.

Customizing Error Messages

We will explain in detail how to customize the default error messages. This includes how to open the validation.php file and add custom attribute names (Japanese display names for table columns) step by step.

Open the file that contains the error message output rules:

/resources/lang/ja/validation.php

The file contains content like the following:

<?php

return [
    'accepted'             => ':attribute must be accepted.',
    'active_url'           => ':attribute is not a valid URL.',

~

];
?>

Practical Example

Here’s a practical example of changing actual table column names (e.g., sei, mei, seiza, ketuekigata, syussin) to more user-friendly Japanese labels (e.g., 姓, 名, 星座, 血液型, 出身地).

Add an attributes array inside the return [ ~ ] in the validation.php file.

For the table column names:

sei, mei, seiza, ketuekigata, syussin

Use the Japanese labels:

姓, 名, 星座, 血液型, 出身地

Here is an example of how to add them. (Lines 9–15 are the added lines):

<?php
return [
    'accepted'             => ':attribute must be accepted.',
    'active_url'           => ':attribute is not a valid URL.',

~

    'attributes' => [
        'sei'   => '姓',
        'mei' => '名',
        'seiza' => '星座',
        'ketuekigata'    => '血液型',
        'syussin'   => '出身地',
    ],

];
?>

Conclusion

In this article, we introduced the benefits of localizing validation error messages and best practices for doing so. By focusing on customizing form validation in Laravel and changing error messages to Japanese, you can develop more user-friendly and easily understandable web applications.

*Tested on Laravel version 6.18.39.

*Please use at your own discretion if reusing this content.