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
Laravel News Partners

Laravel Jobs

Senior Full-Time Laravel Developer (REMOTE)
Remote, ANYWHERE
Vue School
Senior Laravel Developer
Remote, USA & Canada Only
Givecloud
Backend Software Engineer
Remote, USA Only
CommentSold
Backend Software Engineer (x/f/m)
Remote
Smartbnb
Senior Developer
Remote
Shelterluv

Newsletter

Join 31,000+ others and never miss out on new tips, tutorials, and more.