Enable user Timezones in your application.

Overview

Laravel Timezone

Latest Version on Packagist Total Downloads Licence Quality Score StyleCI Buy us a tree Treeware (Trees)

An easy way to set a timezone for a user in your application and then show date/times to them in their local timezone.

How does it work

This package listens for the \Illuminate\Auth\Events\Login event and will then automatically set a timezone on your user model (stored in the database).

This package uses the torann/geoip package which looks up the users location based on their IP address. The package also returns information like the users currency and users timezone. You can configure this package separately if you require.

How to use

You can show dates to your user in their timezone by using

{{ Timezone::convertToLocal($post->created_at) }}

Or use our nice blade directive

@displayDate($post->created_at)

More examples below

Installation

Pull in the package using Composer

composer require jamesmills/laravel-timezone

Publish database migrations

php artisan vendor:publish --provider="JamesMills\LaravelTimezone\LaravelTimezoneServiceProvider" --tag=migrations

Run the database migrations. This will add a timezone column to your users table.

php artisan migrate

Examples

Showing date/time to the user in their timezone

Default will use the format jS F Y g:i:a and will not show the timezone

{{ Timezone::convertToLocal($post->created_at) }}

// 4th July 2018 3:32:am

If you wish you can set a custom format and also include a nice version of the timezone

{{ Timezone::convertToLocal($post->created_at, 'Y-m-d g:i', true) }}

// 2018-07-04 3:32 New York, America

Using blade directive

Making your life easier one small step at a time

@displayDate($post->created_at)

// 4th July 2018 3:32:am

And with custom formatting

@displayDate($post->created_at, 'Y-m-d g:i', true)

// 2018-07-04 3:32 New York, America

Saving the users input to the database in UTC

This will take a date/time, set it to the users timezone then return it as UTC in a Carbon instance.

$post = Post::create([
    'publish_at' => Timezone::convertFromLocal($request->get('publish_at')),
    'description' => $request->input('description'),
]);

Custom Configuration

Publishing the config file is optional.

php artisan vendor:publish --provider="JamesMills\LaravelTimezone\LaravelTimezoneServiceProvider" --tag=config

Flash Messages

When the timezone has been set, we display a flash message, By default, is configured to use Laravel default flash messaging, here are some of the optional integrations.

laracasts/flash - 'flash' => 'laracasts'

mercuryseries/flashy - 'flash' => 'mercuryseries'

spatie/laravel-flash - 'flash' => 'spatie'

mckenziearts/laravel-notify - 'flash' => 'mckenziearts'

To override this configuration, you just need to change the flash property inside the configuration file config/timezone.php for the desired package. You can disable flash messages by setting 'flash' => 'off'.

Overwrite existing timezones in the database

By default, the timezone will be overwritten at each login with the current user timezone. This behavior can be restricted to only update the timezone if it is blank by setting the 'overwrite' => false, config option.

Default Format

By default, the date format will be jS F Y g:i:a. To override this configuration, you just need to change the format property inside the configuration file config/timezone.php for the desired format.

Lookup Array

This lookup array configuration makes it possible to find the remote address of the user in any attribute inside the Laravel request helper, by any key. Having in mind when the key is found inside the attribute, that key will be used. By default, we use the server attribute with the key REMOTE_ADDR. To override this configuration, you just need to change the lookup property inside the configuration file config/timezone.php for the desired lookup.

Underlying GeoIp Package

If you wish to customise the underlying torann/geoip package you can publish the config file by using the command below.

php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

License

This package is 100% free and open-source, under the MIT license. Use it however you want.

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

Issues

If you receive a message like This cache store does not support tagging this is because the torann/geoip package requires a caching driver which supports tagging and you probably have your application set to use the file cache driver. You can publish the config file for the torann/geoip package and set 'cache_tags' => null, to solve this. Read more about this issue here.

Comments
  • No way of getting user IP when behind a load balancer

    No way of getting user IP when behind a load balancer

    It seems that timezone is always saved as "America/New_York". This seems to be some sort of default / localhost value.

    I now have to do another check after login to see if NULL or "America/New_York" and update accordingly.

    All of my calls to geoip()->getLocation() seem to work correctly, so don't know what's happening in in this library's Login listener that fails.

    opened by RykWaters 12
  • use in model

    use in model

    i want to use this command in my model like this:

        public function getTimeAttribute($value){
            return Timezone::convertFromLocal($this->start);
        }
    

    but it returns this error: Class 'App\Timezone' not found

    opened by MohammaddReza 8
  • Ability to provide a lookup table to fetch the remote address.

    Ability to provide a lookup table to fetch the remote address.

    Related to issue #8

    @jamesmills & @ridz1208 I did some initial implementation on that issue, please take a look and feel free to add comments, commits, etc. ;)

    I initially thought of creating a lookup table so we can search in whatever attribute inside the request helper, by any key. Having in mind when the key is found inside the attribute, that key will be used.

    opened by amandiobm 6
  • Invalid argument supplied for foreach()

    Invalid argument supplied for foreach()

    Hello!

    Installed as shown, but once i Login i Get the message "Invalid argument supplied for foreach()".

    here:

            /**
    
        * @return mixed
    
        */
    
        private function getFromLookup()
    
        {
    
            $result = null;
    
     
    
            foreach (config('timezone.lookup') as $type => $keys) {
    
                if (empty($keys)) {
    
                    continue;
    
                }
    
     
    
                $result = $this->lookup($type, $keys);
    
     
    
                if (is_null($result)) {
    
                    continue;
    
                }
    
            }
    
     
    
            return $result;
    
        }
    
     
    
        /**
    
    opened by sharkyenergy 5
  • [Hot-Fix]: Null as first param on convertToLocal method.

    [Hot-Fix]: Null as first param on convertToLocal method.

    At Timezone::convertToLocal has an if statement which checks if the date is not null. That statement is never reached because the method signature required the first param to be a Carbon Object.

    I had sometimes my date are null which broke the @displayDate directive.

    opened by amandiobm 5
  • Method 'convertFromLocal' should convert local time to Laravel Default Timezone, not UTC

    Method 'convertFromLocal' should convert local time to Laravel Default Timezone, not UTC

    Hi, thanks for great laravel package, i think Method 'convertFromLocal' should convert local time to Laravel Default Timezone, not UTC due some application use different Timezone

    opened by tarikhagustia 4
  • Always saving default timezone on localhost.

    Always saving default timezone on localhost.

    Hi!

    User timezone value are always been saved as 'America/New_York', or wathever the default timezon in geoip config is.

    It is because i'm on localhost? Or maybe I've missed something during installation?

    Thanks in advance!

    opened by maverick504 4
  • Make database migration publishable

    Make database migration publishable

    It would be very useful to make the included migration publishable and to use current date for filename. I am having issues with your package trying to update users table that has not yet been created.

    opened by DariusIII 4
  • UpdateUsersTimezone gives wrong info

    UpdateUsersTimezone gives wrong info

    Hi,

    Thanks for this nice package, I've integrated it on live server, and I'm using ipgeolocation service in geoip package config. So, I found this bug here :

    if (config('timezone.overwrite') == true || $user->timezone == null) {
                    $user->timezone = $geoip_info['timezone'];
                    $user->save();
                    $this->notify($geoip_info);
     }
    

    This : $geoip_info['timezone'] returns Null Here dd($geoip_info) (See Attached) So to fix it : ` $user->timezone = $geoip_info->time_zone['name'];

    bug `

    Thanks.

    bug help wanted good first issue 
    opened by AEK-BKF 3
  • Clearing config before package installation

    Clearing config before package installation

    opened by amandiobm 3
  • Added ability to cast dates from the model using custom cast class

    Added ability to cast dates from the model using custom cast class

    Laravel gives us the ability to use custom classes when casting attributes directly from the model.

    Docs (https://laravel.com/docs/7.x/eloquent-mutators#custom-casts)

    Basic usage

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use JamesMills\LaravelTimezone\Casts\Timezone;
    
    class Foo extends Model
    {
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'created_at' => Timezone::class,
        ];
    }
    

    Advanced usage

    Custom format

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use JamesMills\LaravelTimezone\Casts\Timezone;
    
    class Foo extends Model
    {
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'created_at' => Timezone::class.':Y-m-d H:i:s',
        ];
    }
    

    Return the timezone as a string passing along the format.

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use JamesMills\LaravelTimezone\Casts\Timezone;
    
    class Foo extends Model
    {
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'created_at' => Timezone::class.':d/m/Y H:i:s,true',
        ];
    }
    

    Return the timezone as a string using the default format.

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use JamesMills\LaravelTimezone\Casts\Timezone;
    
    class Foo extends Model
    {
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'created_at' => Timezone::class.':null,true',
        ];
    }
    
    opened by amandiobm 3
  • Fix for Laravel Passport 'loginUsingId does not exist' error

    Fix for Laravel Passport 'loginUsingId does not exist' error

    It is important to note the addition of: use App\Models\User in the modified file... This may not be compatible with earlier versions of Laravel. Is there a way to conditionally use App\Models\User OR App\User depending on the version?

    opened by cedlinx 0
  • Stateless support - Illuminate\\Auth\\RequestGuard::loginUsingId does not exist

    Stateless support - Illuminate\\Auth\\RequestGuard::loginUsingId does not exist

    It seems like this package doesn't support stateless requests (only web middleware). If we aren't using Web routes, we get Illuminate\\Auth\\RequestGuard::loginUsingId does not exist - how can we use this? Thanks for the help.

    opened by logan-jobzmall 2
  • Take the first found IP from 'lookup' config key

    Take the first found IP from 'lookup' config key

    At this moment, if IP is not found, the loop skips but eventually the last resolved IP is taken.

    IMHO it should be the first IP grabbed, for example I'd like to get real user IP from cloudflare using this code:

    'lookup' => [
            'server' => [
                'HTTP_CF_CONNECTING_IP',
                'REMOTE_ADDR',
            ],
            'headers' => [
    
            ],
        ],
    

    Now, I need to use 'HTTP_CF_CONNECTING_IP' as the last option which is not intuitive, and we unnecessarily loop through all the items.

    Solves: https://github.com/jamesmills/laravel-timezone/issues/78

    opened by boryn 0
  • The library does not take the first found IP from 'lookup' config key

    The library does not take the first found IP from 'lookup' config key

    At this moment, the library takes the last found IP from the 'lookup' config key. In documentation there is written "Having in mind when the key is found inside the attribute, that key will be used.", and I believe it should be the first taken.

    I'd go with this changes to the lookup() method:

    private function lookup($type, $keys)
        {
            $value = null;
    
            foreach ($keys as $key) {
                if (request()->$type->has($key)) {
                    return request()->$type->get($key);
                }
            }
    
            return $value;
        }
    
    opened by boryn 1
Releases(1.0.6)
Owner
James Mills
James Mills
A package can enable DKIM for your Laravel mails.

TobyMaxham Laravel DKIM This package can be used to add a DKIM signature to your outgoing mails. Instead of changing the default Laravel Mailer, Larav

Tobias Maxham 2 Apr 14, 2022
Adds a service worker to Magento2 to enable PWA features

Monsoon PWA Adds icons, a web manifest file and a service-worker file to make magento 2 a PWA. Main Features Supports Magento Blank and Luma as well a

Monsoon Consulting 20 Nov 17, 2022
A simple laravel package to enable cascade deleting on polymorphic relations.

Morph Cascade Delete A simple laravel package to enable cascade deleting on polymorphic relations. Installation Install with composer composer requi

Moataz Hajres 18 May 15, 2022
Enable/disable query logger in Laravel/Lumen

Enable/disable query logger in Laravel/Lumen

Ngoc Linh Pham 5 Nov 2, 2022
User authentication REST API with Laravel (Register, Email verification, Login, Logout, Logged user data, Change password, Reset password)

User Authentication API with Laravel This project is a user authentication REST API application that I developed by using Laravel and MySql. Setup Fir

Yusuf Ziya YILDIRIM 3 Aug 23, 2022
A Multi User Chat Application With Laravel and Livewire

A Multi User Chat Application With Laravel and Livewire. where you can chat with multiple frinds at the same time. i build this with php Laravel and Livewire.

Tauseed 15 Oct 22, 2022
This package helps you to add user based follow system to your model.

Laravel Follow User follow unfollow system for Laravel. Related projects: Like: overtrue/laravel-like Favorite: overtrue/laravel-favorite Subscribe: o

安正超 1k Dec 31, 2022
Laravel Podcast is Laravel 5.5 web app that enables you to manage RSS feeds for your favorite podcasts and listen to the episodes in a seamless UI and User Authentication.

Laravel Podcast is Laravel 5.5 web app that enables you to manage RSS feeds for your favorite podcasts and listen to the episodes in a seamless UI and

Jeremy Kenedy 35 Dec 19, 2022
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

null 9 Dec 14, 2022
Allow your model to record the creation, update and deletion of user fingerprints in laravel packages

This laravel package will allow your models to record the the created, updated and deleted by User FingerPrints

Managemize 4 Mar 11, 2022
Automatically load your helpers in your laravel application.

Laravel AutoHelpers Automatically load your helpers in your laravel application. Installation You can install the package via composer: composer requi

Florian Wartner 6 Jul 26, 2021
Simple user messaging package for Laravel

Laravel Messenger This package will allow you to add a full user messaging system into your Laravel application. Leave some feedback How are you using

Chris Gmyr 2.3k Dec 29, 2022
User to Team associations with invitation system for the Laravel 5 Framework

Teamwork This package supports Laravel 6 and above. Teamwork is the fastest and easiest method to add a User / Team association with Invites to your L

Marcel Pociot 983 Jan 2, 2023
A package to validate email domains in a user registration form

This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM 56 Jul 19, 2022
Per-user settings repository system for Laravel

Laraconfig Per-user settings repository system for Laravel. This package allows users to have settings that can be queried, changed and even updated,

Italo 170 Oct 26, 2022
Laravel Authentication Log is a package Log user authentication details and send new device notifications.

Laravel Authentication Log is a package which tracks your user's authentication information such as login/logout time, IP, Browser, Location, etc. as well as sends out notifications via mail, slack, or sms for new devices and failed logins.

Anthony Rappa 540 Jan 5, 2023
This package provides you with a simplistic `php artisan make:user` command

Laracademy Generators Laracademy make:user Command - provides you with a simplistic artisan command to generate users from the console. Author(s): Lar

Laracademy 18 Jan 19, 2019
Thunder is an advanced Laravel tool to track user consumption using Cashier's Metered Billing for Stripe. ⚡

⚡ Thunder Thunder is an advanced Laravel tool to track user consumption using Cashier's Metered Billing for Stripe. ⚡ ?? Supporting If you are using o

Renoki Co. 10 Nov 21, 2022
A package to validate email domains in a user registration form

Laravel Email Domain Rule This package allows to define a subset of allowed email domains and validate any user registration form with a custom rule.

H-FARM Innovation 56 Jul 19, 2022