Search code examples
phplaravelphp-carbon

Laravel best way of using setlocale with carbon


I am new to the laravel framework and OOP. I am building a small webapp.

One of the things what comes back every time on the website is the date of today. To generate the date of today I use Carbon like so

{{ carbon\carbon::today()->formatLocalized(' %d %B %Y') }} in my view.

That works fine and gives me back the following: "1 March 2017". Because my application is suppose to be in dutch i've searched for a function to set the dates to dutch. I've found this: setlocale(LC_ALL, 'nl_NL'); What works just fine except I have to add it to every controller method I use for the views where I need the date.

Is there a better/cleaner solution for this? Like somewhere I can set it global.


Solution

  • Two ways:

    1) a BaseController class, in the __construct() you can use setlocale(), next you derive every localized controller from the BaseController class. 2) in a middleware

    Dont know if your locale can change per request (i.e. ?locale=xx), is stored on authenticad user or others way, but the 2 methods above should works with fixed or changing locale.

    I use the middleware way:

     public function handle($request, Closure $next)
     {
        $locale = false;
        if(Auth::user()){
            $locale = Auth::user()->locale;
        }elseif(session()->has('locale')) {
            $locale = session('locale');
        }elseif($request->has('locale')) {
            $locale = request('locale');
        }
        if($locale && array_key_exists($locale, config('app.locales'))) {
            app()->setLocale($locale);
            setlocale(LC_ALL, $locale);
        }
        return $next($request);
    }