Get User’s local timezone with Laravel 5.x
Recently I saw someone asking a question on the Facebook Laravel Group about “how to get user’s local timezone by their own geolocation ?”.
I also wondered how to do that ?. I usually do setting timezone on the Config/App.php then I changed the ‘timezone’ => ‘Asia/Jakarta’ based on my country belongs. Done! Nothing special ! :D
Okay, let’s back to the question above!
So, I googled it to find the answers then I found it. Someone has also been asking in Laracasts with the similar questions. link here
Some user named socialmosaic had interesting answers.
Here’s the answers:
- Get the user’s IP address http://ipecho.net/plain
- Convert the IP along with json file then put the IP address of user on http://ip-api.com/json/ (user’s IP).
Example:
http://ip-api.com/json/123.123.234.232Okay, let’s implement the logic above on Laravel 5.x
Step 1 : Create helper.php in the App file folder.
Step 2 : Autoload Composer
Register helper on composer.json add files array inside autoload section
“autoload”: {
“classmap”: [“database”],
“psr-4”: {“App\\”: “app/”},
“files” : [“app/Helper.php”]
}don’t forget to composer dump-autoload on your CLI terminal
Step 3 : Using Helper Function
- Through Controller
- Or in the blade template directly
<p> {{ Carbon\Carbon::now(get_local_time()) }} </p>Done!
P.s: Anyway, sorry for my english mistaken grammar.
Links references: