Using Carbon with Laravel Doctrine

This is a quick instruction how to use Carbon php with Doctrine 2 ORM and Laravel framework.

With Laravel I'm used to using Carbon which has more features and nice interface.

When you install laravel-doctrine you will have Doctrine's default behavior. It uses DateTime class when it fetch datetime field from database.

This is my solution how to tell Doctrine to use Carbon:

Create app/Doctrine/CarbonType.php class with content:

namespace App\Doctrine;


use Carbon\Carbon;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\DateTimeType;

class CarbonType extends DateTimeType
{
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return Carbon::instance(parent::convertToPHPValue($value, $platform));
    }

}

This is easies way to wrap default DateTime type with Carbon.

Open app/Providers/AppServiceProvider.php and tell doctrine to use this new class for datetime column types. Add \Doctrine\DBAL\Types\Type::overrideType('datetime', CarbonType::class); in boot

You can probably add for other date types like time and date but I haven't tried that.

Author

I plan to write more articles about common laravel components. If you are interested let’s stay in touch.
comments powered by Disqus