jamesmills / laravel-timezone

Enable user Timezones in your application.
MIT License
677 stars 91 forks source link

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

Closed amandiobm closed 4 years ago

amandiobm commented 4 years ago

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',
    ];
}
jamesmills commented 4 years ago

This is crazy amazing. Thank you @amandiobm.

jamesmills commented 4 years ago

wow!

amandiobm commented 4 years ago

Close and moved to #35