Skip to content

Instantly share code, notes, and snippets.

@amin3536
Created June 11, 2023 08:43
Show Gist options
  • Save amin3536/a8ca2258461bff689e71e08be8dd106a to your computer and use it in GitHub Desktop.
Save amin3536/a8ca2258461bff689e71e08be8dd106a to your computer and use it in GitHub Desktop.

VertaCast

Verata is casting a Laravel cast class to read or write values in Georgia format in the database. However, you can receive the output in Jalil format. Additionally, you can use Jalil string format or Carbon as input to save data.

usage

'created_at' => VertaCast::class.':Y-n-j,Y-n-j hh:mm'

Y-n-j represents the output format.

Y-n-j hh:mm represents the input format, assuming the input is a valid Jalil and string.

Note:

All dates are written in Georgia time format in the database.

Please let me know if there's anything else I can assist you with!

<?php
namespace App\Casts;
use Carbon\Carbon;
use Hekmatinasser\Jalali\Exceptions\InvalidDatetimeException;
use Illuminate\Contracts\Database\Eloquent\Castable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Verta;
use function League\Uri\validate;
class VertaCast implements Castable
{
// ...
/**
* Get the caster class to use when casting from / to this cast target.
*
* @param array<string, mixed> $arguments
*/
public static function castUsing(array $arguments): CastsAttributes
{
return new class ($arguments) implements CastsAttributes {
private $arguments;
public function __construct(array $arguments)
{
$this->arguments = $arguments;
}
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
if ($this->arguments[0] ?? false) {
return verta($value)->format($this->arguments[0]);
}
return verta($value);
}
/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
try {
if (!is_string($value)) {
return $value;
}
//pass custom format in casting like 'created_at' => VertaCast::class.':Y-n-j,Y-n-j',
if ($this->arguments[1] ?? false) {
return Verta::parseFormat($this->arguments[1], $value)->toCarbon();
}
//value format must be '1395-10-07 14:12:32' or '1396 مهر 17'
return Verta::parse($value)->toCarbon();
}catch (\Exception $e){
return $value;
}
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment