Laravel App Change TimeZone dynamically

Hello,

Recently I was working on mobile app where we have APIs return in Laravel. We were handling some date and times on server side. This dates and time from server side was displayed to mobile users. Now mobile users can be in different timezones and so APIs should set timezones and show dates and time according to timezone. Here is how I implemented it. I saved user’s timezone in db and for each API request from that user set timezone from database.

First extend a laravel controller with base controller so we don’t need to repeat this code everywhere.

class ApiController extends BaseController {
    public function __construct() {
         parent::__construct();
    }
}

Now go to BaseController and add constructor.

class BaseController {
        $employeeId = null;
        if(Input::has(’employee_id’)){
              $employeeId = Input::get(’employee_id’);
        }

        if($employeeId!=null){
            $employeeDetails = EmployeeDetails::find($employeeId);
            if($employeeDetails->timezone != null){
                Config::set(‘app.timezone’, $employeeDetails->timezone);
                date_default_timezone_set($employeeDetails->timezone);
            }
        }
}

That’s it and now you will have dynamic timezone as per user.

This entry was posted in Laravel, PHP, PHP Framework on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *