PHP code example of atymic / laravel-dateinterval-cast

1. Go to this page and download the library: Download atymic/laravel-dateinterval-cast library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

atymic / laravel-dateinterval-cast example snippets


class TestModel extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_xyz' => 'boolean',
        'date_interval' => DateIntervalCast::class,
        'carbon_interval' => CarbonIntervalCast::class,
    ];
}

$model = new TestModel();

$model->carbon_interval = now()->subHours(3)->diffAsCarbonInterval();

$model->save(); // Saved as `P3H`
$model->fresh();

$model->carbon_interval; // Instance of `CarbonInterval`
$model->carbon_interval->forHumans(); // prints '3 hours ago'

try {
    $model->carbon_interval = 'not_a_iso_period'; 
} catch (\Atymic\DateIntervalCast\Exception\InvalidIsoDuration $e) {
    // Exception thrown if you try to assign an invalid duration
}