3
0

More than 3 years have passed since last update.

Laravelで多言語処理を行う

Last updated at Posted at 2020-05-15

目次

Laravelの記事一覧は下記
PHPフレームワークLaravelの使い方

Laravelバージョン

動作確認はLaravel Framework 7.19.1で行っています

前提条件

eclipseでLaravel開発環境を構築する。デバッグでブレークポイントをつけて止める。(WindowsもVagrantもdockerも)
本記事は上記が完了している前提で書かれています
プロジェクトの作成もapacheの設定も上記で行っています

メッセージファイル作成

(1) /sample/resources/lang/en/messages.phpを作成

en/messages.php
<?php

return [
    'sample' => 'sample message'
];

(2) /sample/resources/lang/jaフォルダを作成
(3) /sample/resources/lang/ja/messages.phpを作成

ja/messages.php
<?php

return [
    'sample' => 'サンプルメッセージ'
];

Controllerにメソッド追加

(1) /sample/app/Http/Controllers/SampleController.phpに下記を追記
use Illuminate\Support\Facades\App;

(2) /sample/app/Http/Controllers/SampleController.phpにmultiLangメソッドを追記

    public function multiLang(Request $request)
    {
        if ($request->query('lang') === 'ja') {
            App::setLocale('ja');
        } else {
            App::setLocale('en');
        }
        $data = [
            'msg' => __('messages.sample'),
        ];
        return view('sample.multiLang', $data);
    }

App::setLocaleメソッドを使うことによってresources/langフォルダ内のどのフォルダを使うか設定することができます
App::setLocaleメソッドを呼ばなかった場合、config/app.php内のlocaleが使われます
__('messages.sample')でmessages.php内のsample要素の値を取得できます

(3) /sample/routes/web.phpに下記を追記
Route::get('sample/multi-lang', 'SampleController@multiLang');

viewの作成

/sample/resources/views/sample/multiLang.blade.phpファイル作成

multiLang.blade.php
<html>
    <head>
        <title>sample</title>
    </head>
    <body>
        <div>{{ $msg }}</div>
        <div>@lang('messages.sample')</div>
    </body>
</html>

bladeでは@lang('messages.sample')でmessages.php内のsample要素の値を取得できます
{{ __('messages.welcome') }}と書いても取得できます

動作確認

http://localhost/laravelSample/sample/multi-lang

sample message
sample message

http://localhost/laravelSample/sample/multi-lang?lang=ja

サンプルメッセージ
サンプルメッセージ
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0