|
1 | 1 | # Dates Timezone Conversion Trait
|
| 2 | + |
2 | 3 | This package provides a trait that automatically converts an Eloquent
|
3 | 4 | model's dates to and from the current user's timezone.
|
| 5 | + |
| 6 | +## Installation |
| 7 | + |
| 8 | +Dates Timezone Conversion Trait can be easily installed using Composer. |
| 9 | +Just run the following command from the root of your project. |
| 10 | + |
| 11 | +``` |
| 12 | +composer require divineomega/dates-timezone-conversion-trait |
| 13 | +``` |
| 14 | + |
| 15 | +If you have never used the Composer dependency manager before, head |
| 16 | +to the [Composer website](https://getcomposer.org/) for more |
| 17 | +information on how to get started. |
| 18 | + |
| 19 | +## Usage |
| 20 | + |
| 21 | +First, you must add a `timezone` field to your application's main `User` |
| 22 | +model and populate it will an appropriate timezone. Please see this [list |
| 23 | + of supported timezones](https://secure.php.net/manual/en/timezones.php). |
| 24 | + |
| 25 | +Then, to benefit from this trait, simply `use` it within any Eloquent Model. |
| 26 | +An example of a `User` model with the trait being used is shown below. |
| 27 | + |
| 28 | +```php |
| 29 | +<?php |
| 30 | + |
| 31 | +namespace App\Models; |
| 32 | + |
| 33 | +use DivineOmega\DatesTimezoneConversion\Traits\DatesTimezoneConversion; |
| 34 | +use Illuminate\Notifications\Notifiable; |
| 35 | +use Illuminate\Foundation\Auth\User as Authenticatable; |
| 36 | + |
| 37 | +class User extends Authenticatable |
| 38 | +{ |
| 39 | + use Notifiable, DatesTimezoneConversion; |
| 40 | + |
| 41 | + protected $dates = [ |
| 42 | + 'last_logged_in_at', |
| 43 | + 'created_at', |
| 44 | + 'updated_at' |
| 45 | + ]; |
| 46 | + |
| 47 | + /* snipped */ |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +After using the trait, the following transformation will automatically be |
| 52 | +applied to any attributes defined in the model's `$dates` array, if a |
| 53 | +user is currently logged in. |
| 54 | + |
| 55 | +* When reading an attribute (e.g. `$user->last_logged_in_at`), the datetime |
| 56 | +object will automatically be converted to the user's timezone. |
| 57 | + |
| 58 | +* When writing to an attribute (e.g. `$user->last_logged_in_at`), the datetime |
| 59 | +will automatically be converted to the Laravel application's timezone (as |
| 60 | +defined in the `config/app.php` file). |
0 commit comments