maartenpaauw / laravel-date-time-zone-cast
A Laravel cast to convert strings to DateTimeZone instances
Fund package maintenance!
Maarten Paauw
Requires
- php: ^8.2
- illuminate/contracts: ^12.18
- illuminate/database: ^12.18
Requires (Dev)
- larastan/larastan: ^3.6
- laravel/pint: ^1.24
- nunomaduro/collision: ^8.8
- orchestra/testbench: ^10.4
- pestphp/pest: ^3.8
- pestphp/pest-plugin-arch: ^3.1
- pestphp/pest-plugin-laravel: ^3.2
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-phpunit: ^2.0
README
A Laravel cast that allows you to store and retrieve DateTimeZone
objects in your Eloquent models. This cast
automatically converts timezone strings (e.g. 'Europe/Amsterdam') to PHP DateTimeZone
instances and vice versa when
interacting with your database.
Support Me
You can support me by buying Model States for Filament.
Installation
You can install the package via composer:
composer require maartenpaauw/laravel-date-time-zone-cast
Usage
1. Add the Cast to Your Model
Add the cast to your Eloquent model's $casts
array:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Maartenpaauw\LaravelDateTimeZoneCast\DateTimeZoneCast; class User extends Model { protected $casts = [ 'timezone' => DateTimeZoneCast::class, ]; }
2. Database Schema
Ensure your database column is set up to store timezone strings:
Schema::table('users', function (Blueprint $table) { $table->string('timezone')->nullable(); });
3. Working with the Model
$user = new User(); $user->timezone = 'Europe/Amsterdam'; $user->save(); $timezone = $user->timezone; // DateTimeZone instance echo $timezone->getName(); // 'Europe/Amsterdam'
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
License
The MIT License (MIT). Please see License File for more information.