PHP code example of jn-jairo / laravel-cast
1. Go to this page and download the library: Download jn-jairo/laravel-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/ */
jn-jairo / laravel-cast example snippets
print_r(Cast::cast('{"foo":"bar"}', 'array'));
/*
Array
(
[foo] => bar
)
*/
print_r(Cast::castDb(1234.555, 'decimal', '10:2'));
// 1234.56
print_r(Cast::castDb(['foo' => 'bar'], 'json'));
// {"foo":"bar"}
print_r(Cast::castJson(new DateTime('01 jan 2000'), 'date'));
// 2000-01-01
$decrypted = Cast::cast($encrypted, 'encrypted');
$encrypted = Cast::castDb($decrypted, 'encrypted');
$decrypted = Cast::castJson($encrypted, 'encrypted');
$decompressed = Cast::cast($compressed, 'compressed');
$compressed = Cast::castDb($decompressed, 'compressed');
$decompressed = Cast::castJson($compressed, 'compressed');
$decoded = Cast::cast('base64:Rm9vQmFy', 'base64', 'base64:'); // FooBar
$encoded = Cast::castDb('FooBar', 'base64', 'base64:'); // base64:Rm9vQmFy
$decoded = Cast::castJson('base64:Rm9vQmFy', 'base64', 'base64:'); // FooBar
$array = Cast::cast('q1ZKy89XslJKSixSqgUA', 'pipe', '|base64|compressed|array|'); // ['foo' => 'bar']
$base64Compressed = Cast::castDb(['foo' => 'bar'], 'pipe', '|base64|compressed|array|'); // q1ZKy89XslJKSixSqgUA
$array = Cast::castJson('q1ZKy89XslJKSixSqgUA', 'pipe', '|base64|compressed|array|'); // ['foo' => 'bar']
enum MyEnum : int
{
case foo = 1;
case bar = 2;
}
Cast::cast(1, 'enum', MyEnum::class); // MyEnum::foo
Cast::castDb(MyEnum::foo, 'enum', MyEnum::class); // 1
Cast::castJson(MyEnum::foo, 'enum', MyEnum::class); // 1
use Illuminate\Contracts\Support\Arrayable;
enum MyEnum : string implements Arrayable
{
case foo = 1;
case bar = 2;
public function description() : string
{
return match ($this) {
self::foo => 'foo description',
self::bar => 'bar description',
};
}
public function toArray()
{
return [
'name' => $this->name,
'value' => $this->value,
'description' => $this->description(),
];
}
}
Cast::cast(1, 'enum', MyEnum::class); // MyEnum::foo
Cast::castDb(MyEnum::foo, 'enum', MyEnum::class); // 1
Cast::castJson(MyEnum::foo, 'enum', MyEnum::class);
// [
// 'name' => 'foo',
// 'value' => 1,
// 'description' => 'foo description'
// ]
class CustomType implements \JnJairo\Laravel\Cast\Contracts\Type
{
// ...
}
class CustomType extends \JnJairo\Laravel\Cast\Types\Type
{
// ...
}
// config/cast.php
return [
'types' => [
'custom_type' => CustomType::class,
],
];
Cast::cast('foo', 'custom_type');
bash
php artisan vendor:publish --provider=JnJairo\\Laravel\\Cast\\CastServiceProvider