Created
October 8, 2019 15:16
-
-
Save Gummibeer/6dbe8bef75f521c6ca3be1f3b3e46d28 to your computer and use it in GitHub Desktop.
set all locales if app locale changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\RedirectResponse; | |
use Illuminate\Http\Request; | |
class Localized | |
{ | |
/** | |
* @param Request $request | |
* @param Closure $next | |
* | |
* @return RedirectResponse|mixed | |
*/ | |
public function handle(Request $request, Closure $next) | |
{ | |
$locale = $request->route('language'); | |
if (! in_array($locale, config('app.locales'))) { | |
// do something if the locale is unknown `app.locales` is a custom config value | |
} | |
app()->setLocale($locale); | |
return $next($request); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Listeners; | |
use Carbon\Carbon; | |
use Illuminate\Foundation\Events\LocaleUpdated; | |
use Illuminate\Support\Facades\URL; | |
class SetAppLocale | |
{ | |
public function handle(LocaleUpdated $event): void | |
{ | |
setlocale(LC_ALL, $event->locale); | |
URL::defaults([ | |
'language' => $event->locale, | |
]); | |
Carbon::setLocale($event->locale); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use App\Listeners\SetAppLocale; | |
use Illuminate\Foundation\Events\LocaleUpdated; | |
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; | |
class EventServiceProvider extends ServiceProvider | |
{ | |
protected $listen = [ | |
LocaleUpdated::class => [ | |
SetAppLocale::class, | |
], | |
]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Route::group([ | |
'middleware' => ['localized'], | |
'prefix' => '{language}', | |
], function (): void { | |
// your localized routes | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment