PHP code example of vicgutt / laravel-auto-model-cast

1. Go to this page and download the library: Download vicgutt/laravel-auto-model-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/ */

    

vicgutt / laravel-auto-model-cast example snippets


declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use VicGutt\AutoModelCast\Contracts\AutoCastable;
use VicGutt\AutoModelCast\Concerns\HasAutoCasting;

final class MyModel extends Model implements AutoCastable
{
    use HasAutoCasting;
}

// a migration file
Schema::create('examples', function (Blueprint $table): void {
    $table->json('extras');
});

// a model file
use Illuminate\Database\Eloquent\Casts\AsCollection;

final class Example extends Model implements AutoCastable
{
    use HasAutoCasting;

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'extras' => AsCollection::class,
    ];
}

protected $casts = [
    'extras' => 'json', // or AsArrayObject::class
];

Casts::new()->discoverModelsUsing(
    directory: app_path('Models'),
    basePath: app_path(),
    baseNamespace: 'App',
);

use VicGutt\AutoModelCast\Support\TypeMapper;

final class MyCustomTypeMapper extends TypeMapper
{
    //
}

Casts::new()->useTypeMapper(MyCustomTypeMapper::class);

use VicGutt\InspectDb\Entities\Column;
use Illuminate\Database\Eloquent\Model;
use VicGutt\AutoModelCast\Support\Casters\BaseCaster;

final class MyCustomCaster extends BaseCaster
{
    public function handle(Column $column, Model $model): ?string
    {
       //
    }
}

Casts::new()->useDefaultCaster(MyCustomCaster::class);

Casts::new()->withCustomCasters([
    \App\Models\User::class => \App\Support\AutoCast\Casters\UserCustomCaster::class,
]);

Casts::new()->withDefaultTypesMap([
    DoctrineTypeEnum::BIGINT->value => CastTypeEnum::INT->value,
    DoctrineTypeEnum::DATE->value => CastTypeEnum::IMMUTABLE_DATE->value,
    DoctrineTypeEnum::JSON->value => CastTypeEnum::AS_ARRAY_OBJECT_CLASS->value,
]);

$model = new MyModel;

$casts = $model->getAutoCasts();

// Or
$casts = Casts::for($model::class);

// Or
$casts = Casts::for($model);

// Or
$casts = config("auto-model-cast.casts.{$model::class}", []);

Schema::create('...', function (Blueprint $table): void {
    $table->year('birth_year');
    $table->year('adulthood_year');
});

//

$model->create([
    'birth_year' => '2000',
    'adulthood_year' => 2018,
]);
bash
php artisan vendor:publish --tag="laravel-auto-model-cast-config"