Laravel Formatters
This package is a collection of classes you can use to standardize data formats in your Laravel application. It uses the Service Container to easily extend or override the formatter classes.
The package requires PHP 8.0 and Laravel 8.x. Future versions of PHP & Laravel will be supported.
Available formatters
... Will be more formatters soon.
Contributing
If you have written your own formatter and want to add it to this package, PRs are welcomed.
- Note: PRs won't be accepted without tests!
Installation
You can install the package via composer:
composer require michael-rubel/laravel-formatters
Usage
format(DateTimeFormatter::class, now()->addMonth()) // as `Carbon` instance
format(DateTimeFormatter::class, '2022-12-25 00:00:00') // as string timestamp
Use can pass the string instead of ::class:
format('date_time', '2022-12-25 00:00:00') // 2022-12-25 00:00
format('table_column', 'created_at') // Created at
You can configure the string case (snake/kebab
) in the config file.
Extending formatters
Since the formatters are resolved through the Service Container they can be easily overridden by extending bindings.
For example in your Service Provider:
$this->app->extend(DateTimeFormatter::class, function ($formatter) {
$formatter->datetime_format = 'Y.m.d H:i';
return $formatter;
});
- Note: You can use Laravel Enhanced Container package for shorter extending syntax.
Adding custom/overriding package formatters
To add a custom formatter you should create the class that implements the MichaelRubel\Formatters\Formatter
interface and put it to the app/Formatters
folder. You can put formatter with the same name as the package's to override the formatter from the package.
You can customize the folder by publishing the config:
php artisan vendor:publish --tag="formatters-config"
Then use custom formatter:
format(YourCustomFormatter::class, [
'to_format' => 'something',
'additional_data' => true,
])
Or by passing the string as an alternative:
format('your_custom', 'Something to format.')
Testing
composer test