Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 6+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 09 Jul, 2025
  • 200 Views
  • Use “Custom Casts” for Smarter Models

Custom Casts in Laravel

Laravel Tip: Use “Custom Casts” for Smarter Models

Tired of repeating the same logic every time you access or save a model attribute?

Laravel lets you build a Custom Cast so a field is automatically transformed when you read or write it.

Repeating Logic Everywhere

// controller
$user->phone = preg_replace('/\D/', '', $request->phone);

With a Custom Cast

Create the Cast

php artisan make:cast PhoneNumberCast


namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class PhoneNumberCast implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        // Format when reading
        return '+91-' . chunk_split($value, 5, '-');
    }
    public function set($model, $key, $value, $attributes)
    {
        // Clean digits before saving
        return preg_replace('/\D/', '', $value);
    }
}

Apply It in the Model

class User extends Model
{
    protected $casts = [
        'phone' => \App\Casts\PhoneNumberCast::class,
    ];
}

Now every time you access $user->phone, it’s formatted automatically, and when you save, it’s sanitized automatically—no extra code in controllers.


Why It’s Awesome

  • Keeps models self-aware
  • Reduces repetitive cleaning/formatting
  • Great for phone, money, JSON, flags, and more.


Share: