PHP code example of vkovic / laravel-custom-casts

1. Go to this page and download the library: Download vkovic/laravel-custom-casts 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/ */

    

vkovic / laravel-custom-casts example snippets


namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'is_admin' => 'boolean',
        'login_count' => 'integer'
        'height' => 'decimal:2'
    ];
}

// File: app/User.php

namespace App;

use App\CustomCasts\NameCast;
use Illuminate\Database\Eloquent\Model;
use Vkovic\LaravelCustomCasts\HasCustomCasts;

class User extends Model
{
    use HasCustomCasts;

    protected $casts = [
        'is_admin' => 'boolean', // <-- Laravel default cast type
        'name' => NameCast::class // <-- Our custom cast class (see the section below)
    ];
}

// File: app/CustomCasts/NameCast.php

namespace App\CustomCasts;

use Vkovic\LaravelCustomCasts\CustomCastBase;

class NameCast extends CustomCastBase
{
    public function setAttribute($value)
    {
        return ucwords($value);
    }

    public function castAttribute($value)
    {
        return $this->getTitle() . ' ' . $value;
    }

    protected function getTitle()
    {
        return ['Mr.', 'Mrs.', 'Ms.', 'Miss'][rand(0, 3)];
    }
}

$user = new App\User;
$user->name = 'john doe';

$user->save();

dd($user->name); // 'Mr. John Doe'

// File: app/CustomCasts/NameCast.php

public function updated()
{
    $attribute = $this->attribute;

    if($this->model->isDirty($attribute)) {
        // Notify admin about name change
    }
}

// File: app/CustomCasts/NameCast.php

// Get the name of the model attribute being casted
dd($this->attribute); // 'name'

// Access our `User` model
dd(get_class($this->model)); // 'App/User'

// File: app/User.php

dd($this->getCustomCasts()); // ['name' => 'App/CustomCasts/NameCast']

protected $casts = [
    'avatar' => 'image' // <-- You prefer this ...
    // ---
    'avatar' => ImageCast::class // <-- ... over this
];

// File: config/app.php

'providers' => [
    // ...

    /*
     * Package Service Providers...
     */
    Vkovic\LaravelCustomCasts\CustomCastsServiceProvider::class

    // ...
]
bash
php artisan vendor:publish --provider="Vkovic\LaravelCustomCasts\CustomCastsServiceProvider"