Laravel Custom Casts Package

Laravel Custom Casts Package

The Laravel Custom Casts package by Vladimir Ković enables you to make your own custom cast types in Eloquent models:

Laravel custom casts works similarly to Laravel attribute casting, but with our custom defined logic (in separated class). Beside casting to our complex types, this package gives us the ability to listen and react to underlying model events.

Here’s an example model utilizing a custom cast class:

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 (follow section below)
    ];
}

With the above model in mind, here’s an example of the custom cast class:

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)];
    }
}

The $value in the setAttribute() method is the raw database value we want to store. This package also enables you to handle model events and react to those events.

You can learn more about this package, get full installation instructions, and view the source code on GitHub at vkovic/laravel-custom-casts.


Filed in: News / packages


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Platform Engineer
Canada
Maple
Intermediate Laravel Developer
Austin, TX
Elevation Energy Group
Sr. PHP Developer
Las Vegas
William Hill
Full Stack Laravel Vue Developer
Remote / Bay Area
ZAM Apps, Inc.
Senior Backend PHP Developer (Symfony) (Remote)
Remote
Project Admission
Intermediate Laravel Developer (No Remote, Toronto Only)
Toronto, Canada
Inkbox Ink Inc
Looking for Senior Full-stack Laravel/React.js Javascript API Developer - Immediate (Full-time)
Remote
ApproveMe // Document Signing