Route::get('lang/{lang}',function($lang){
session()->put('locale', $lang);
return redirect()->back();
});
resources/lang/en/all_module/main.php
<?php
return [
'sign_out' => 'Sign Out',
];
resources/lang/th/all_module/main.php
<?php
return [
'sign_out' => 'ออกจากระบบ',
];
app/http/Middleware/Locale.php
<?php
namespace App\Http\Middleware;
use Closure;
class Locale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(session()->has('locale') && in_array(session()->get('locale'),['en','th']))
{
app()->setLocale(session()->get('locale'));
}
else
{
session()->put('locale','en');
}
return $next($request);
}
}
app/Http/Kernel.php
- หา $middlewareGroups
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Locale::class, <<<< เพิ่มบรรทัดนี้
],
'api' => [
'throttle:60,1',
'bindings',
],
];
เวลาเรียกใช้ใน View ( ปุ่มเปลี่ยนภาษา )
<a href="{{ url('lang/th') }}"><button type="button" class="btn btn-success">TH</button></a>
<a href="{{ url('lang/en') }}"><button type="button" class="btn btn-success">EN</button></a>
เวลาประกาศใช้
<button type="button" class="btn btn-primary">@lang('all_module/main.sign_out')</button>