Arabic Date is not showing in Laravel using Carbon - laravel

i want to show date and days in Arabic format using Carbon. but it's showing in English.
Carbon::setlocale("ar");
echo Carbon::parse()->format('D d F Y');
Result: Sun 12 May 2019
Expected result:
it should show day and month in arabic.

You can use this package instead Date
This package contains language files for the following languages:
Albanian
Arabic
Azerbaijani
Bangla
Basque
Belarusian
Bosnian
And more!
Insatall
composer require jenssegers/date
Usage
use Jenssegers\Date\Date;
Date::setLocale('nl');
echo Date::now()->format('l j F Y H:i:s'); // zondag 28 april 2013 21:58:16
echo Date::parse('-1 day')->diffForHumans(); // 1 dag geleden

Change the config/app.php locale to your lang then apply this code:
or you can change app locale dynamically by:
app()->setLocale('ar');
Then
\Carbon\Carbon::now()->translatedFormat('l')
Or
\Carbon\Carbon::createFromDate($now->year, $now->month, $day)->translatedFormat('l')
and so on...

Carbon::setLocale() is only for the diffForHumans method, otherwise it uses the gloabl PHP Datetime locals. So if you want to use Arabic you have to call
setLocale(LC_TIME, $locale);
then use Carbon method formatlocalized()
Carbon\Carbon::now()->formatLocalized($format);
Note that PHP recognizes more than one Arabic locale so you'll have to choose one from this list
Just make sure you pick one that's installed on the server you're working on or the setLocale() method will fail and return false.

Import Carbon ( use Carbon\Carbon; ) In The Top Of Your Controller.
Use Carbon In Your Function Like This :
public function index()
{
Carbon::setLocale('ar');
// Your Code Here...
}
In Your View Use Date Like This:
<p>
{{ \Carbon\Carbon::parse($user->created_at)->translatedFormat('l j F Y H:i:s') }}
</p>

Related

Laravel 8 multilanguage routes and how get the translated link of the same page

I'm trying to make my test app in multilanguage way.
This question has two correlated questions:
First question:
I followed the second answer in How to create multilingual translated routes in Laravel and this help me having a multilanguage site and the route cached, but I've a question and some misunderstanding.
It's a good practice overwrite an app config as they do int the AppServiceProver.php, making:
Config::set('app.locale_prefix', Request::segment(1));
Isn't better to work with the Session::locale in any case?
Second question:
In my case I've two languages, and in the navbar I want to print just ENG when locale is original language, and ITA when session locale is English.
If I'm in the Italian page, the ENG link in the navbar should point to the same English translated page.
Working with the method used in the other question, I hade many problems caused by the:
Config::set('app.locale_prefix', Request::segment(1));
We overwrite the variable in the config file local_prefix, and every time I switch to English language the locale_prefix will change to 'eng' and this sounds me strange, another thing I did is this:
if ( $lang && in_array($lang, config('app.alt_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
We use the alt_langs where are defined only the alternative languages, and this is a problem cause if I pass the local lang, in my case 'it', like lang parameter, this will not be found cause, from the description, the alt_lang should not contain the locale language and you will be able to get only the translated string.
If I change the:
if ( $lang && in_array($lang, config('app.alt_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
in:
if ( $lang && in_array($lang, config('app.all_langs')) ){
return app('url')->route($lang . '_' . $name, $parameters, $absolute);
}
Now using app.all_langs I'm able to choose which URL you want and in which language I want.
How do I get the translated URL?
In the blade file I need to get the translated URL of the page, and if read the other question, we used the $prefix for caching the routes and giving to the route a new name ->name($prefix.'_home'); in this way I can cache all the route and I can call the routes using blade without prefix {{ route('name') }} but, needing the translated url of the actual page a made this on the top of the view:
#php
$ThisRoute = Route::currentRouteName();
$result = substr($ThisRoute, 0, 2);
if ($result =='it' ){
$routeName = str_replace('it_', '', $ThisRoute);
$url = route($routeName,[],true,'en');
} else {
$routeName = str_replace('en_', '', $ThisRoute);
$url = route($routeName,[],true,'it');
}
#endphp
Doing this I get the actual route name that should be it_home I check if start with it_ or en_, I remove the it_ or en_ prefix and I get the translated URL, now you can use the $url as <a href="{{ $url" }}>text</a> cause if I call the {{ route('page') }} I get the link, with the locale language.
This code is not very good, I know, but I written in 5 minutes, need more implementation, and check, but for the moment is just to play with Laravel.
It's a good way?? How can I do it better (except the blade link retrieving)?? Many solution I found used middleware, but I would like to avoid a link in the navbar like mysite.com/changelang?lang=en
Is a good approach overriding the app.locale_prefix?
First
according to your question, it's a bad practice to save the preferences into .env or session because as soon as the session is finished the saved language will be removed also it's common when you need to store any preferences related to your website such as (Color, Font, Language, ...etc) you must store any of them into the cache.
Second
honestly, your code is a very strange and NOT common way and there are two ways to handle what do you need
First
There is a very helpful and awesome package called mcamara it'll help you too much (I recommend this solution).
Second
you can do it from scratch using the lang folder located in the resource folder and you must create files with the same count of the needed languages then use the keys that you'll define into these files into views and you can prefix your routes with the selected language you can use group method like so
Route::group(['prefix' => 'selected_lang'], function() {
Route::get('first_route', [Controller::class, 'your_method']);
});
or you can add the selected language as a query string like so localhost:8000/your_route?lang=en you can follow this tutorial for more info.

Why appears the "GBP10.00" instead of "10.00"?

I have a model where I have this function:
public function showPrice(){
return money_format('%i€', $this->price);
}
Then in the view is used like:
<span>X {{$prod->pshowPrice()}}</span>
But instead of appear 10.00€ appear GBP10.00€.
Do you know why?
i formats the number based on the format used to describe the currency of the current locale
What you're seeing is expected if you're using a locale of en-gb
Something like money_format('%i!', $this->price) will show it with no currency info (where ! is a flag which suppresses the currency symbol)

Using protected $dateFormat throws trailing error

I am trying to format the date at the model using:
protected $dateFormat = "Y-m-d";
and I am getting this error:
"The separation symbol could not be found Trailing data" on line 582 of C:\wamp64\www\israplanet.com\vendor\nesbot\carbon\src\Carbon\Carbon.php
Using
protected $dateFormat = "Y";
causes this error:
"Trailing data" on line 582 of C:\wamp64\www\israplanet.com\vendor\nesbot\carbon\src\Carbon\Carbon.php
This example is from the October docs.
Whats is wrong here?
I'm not familiar with the example you have given (ie: using protected $dateFormat = "Y-m-d";) but when I do something like this I tend to use an accessor on the model:
public function getFormattedDateAttribute($value)
{
return $this->created_at->format('Y-m-d');
}
Obviously created_at would need to be replaced with the name of the date field. You'd then be able to access it in Twig as {{ array.formatted_date }}.
I cannot name this as good answer, but for now i at least can continue.
I simply changed format of the columns (created_at and updated_at) to date format and it stores the way i wanted it, but i always trying to fix problems (this habbit takes a lot of my time).
another option is to use handlebar helper for this.
But i want to understand the problem in the root.
(btw - thanks for answers)

Yii2 change locale formats

I am migrating from Yii 1.x to Yii2.
In Yii 1.x you could define/change the localized formats in a file (sth like /app/i18n/en.php), where you could set all your desired formats, which you could later use.
Now in Yii2 this is gone?
I have 4 languages, each one has different settings. What am i supposed to do if I need a new formatting function?
E.g. I want to make a format for prices in a shop, in each lang differently
DE - 1.234,56
EN - 1,234.567
SK - 1234,5
CZ - 1 234,5678
So I create a new formatter function Yii::$app->formatter->asPrice(1234.567890).
Do I have to program a switch inside the function, and check for the language? That would be very inconvenient, and a lot of duplicity if I need more such functions. And if I had a new language later, I would have to adjust all such functions with a new case.
There must be a better solution. Any ideas?
UPDATE
I think you guys did not get my problem.. I know I can set the locale, and use the asDecimal or similar function. But the problem is that I cannot specifically customize the formatting options - it automatically takes the format defined in the intl PHP extension. I need the possiblity to specifically customize these formats. Maybe e.g. the default for EN is 2 decimals, but I need 3. Where can I set this?
In Yii2 official documentation:
You can use as below:
Yii::$app->formatter->locale = 'en-US';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: January 1, 2014
Yii::$app->formatter->locale = 'de-DE';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: 1. Januar 2014
Yii::$app->formatter->locale = 'ru-RU';
echo Yii::$app->formatter->asDate('2014-01-01'); // output: 1 января 2014 г.
So if you have table with language you can set locale there and in main layout define "Yii::$app->formatter->locale = $lang->locale" where $lang is object of Language model(class) matching current language.
Why dont you want to use asDecimal?
echo Yii::$app->formatter->asDecimal(1234.5678);
DE - 1.234,568
EN - 1,234.568
SK - 1 234,568
CZ - 1 234,568
Or you may try something like:
private $_priceDecimals = [ 'de_DE' => 2, 'en_EN' => 3, 'sk_SK' => 1, 'cz_CZ' => 4];
public function asPrice($value)
{
return $this->asDecimal(
$value,
isset($this->_priceDecimals[$this->locale]) ? $this->_priceDecimals[$this->locale] : null
);
}

Date localization

Can anybody help me with date localization?
My code:
<?php echo date("j F", ($data->create_time)); ?>
And it returns:
1 January
I want to translate this output to Russian language:
1 Января
Yii provides robust i18n functionality through classes such as CDateFormatter and CLocale. You can get an instance of these classes for your application's current language with Yii::app()->getDateFormatter() and Yii::app()->getLocale(). Use these to format your date with a format string either taken straight from the current locale (good if it works for you) or by specifying a custom string:
$formatter = Yii::app()->getDateFormatter();
$format = Yii::app()->getLocale()->getDateFormat('medium'); // use built-in
$format = 'd MMMM'; // or use custom
echo $formatter->format($format, $data->create_time);
i didn't run this code but looks what you are looking for.
http://kr2.php.net/strftime
Udachi^^

Resources