Localizable.php
TLDR
This file contains the Localizable
trait, which includes a method called withLocale
that allows for running a callback with a specified locale.
Methods
withLocale
This method takes a string representing a locale and a callback function as parameters. It runs the callback function with the specified locale. If no locale is provided, the callback function is executed without changing the locale. The method uses the Container
class from the Illuminate\Container
namespace to get the application instance and set the locale. After running the callback function, the method restores the original locale. The method returns the result of the callback function.
<?php
namespace Illuminate\Support\Traits;
use Illuminate\Container\Container;
trait Localizable
{
/**
* Run the callback with the given locale.
*
* @param string $locale
* @param \Closure $callback
* @return mixed
*/
public function withLocale($locale, $callback)
{
if (! $locale) {
return $callback();
}
$app = Container::getInstance();
$original = $app->getLocale();
try {
$app->setLocale($locale);
return $callback();
} finally {
$app->setLocale($original);
}
}
}