Customizing Data Transformations with Laravel Casts

Laravel's custom casts enable tailored data transformations, extending beyond built-in casting capabilities to handle complex data types and business logic. Here is an example of using a phone number formatter using custom casts:

Customizing Data Transformations with Laravel Casts

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

ARE YOU TIRED OF LOW SALES TODAY?

Connect to more customers on doacWeb

Post your business here..... from NGN1,000

WhatsApp: 09031633831

Customizing Data Transformations with Laravel Casts

Laravel's custom casts enable tailored data transformations, extending beyond built-in casting capabilities to handle complex data types and business logic.

Here is an example of using a phone number formatter using custom casts:

And another example of using an address formatter:

 $data['street'],
            'city' => $data['city'],
            'state' => $data['state'],
            'postal_code' => $data['postal_code'],
            'formatted' => sprintf(
                '%s, %s, %s %s',
                $data['street'],
                $data['city'],
                $data['state'],
                $data['postal_code']
            )
        ];
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): string
    {
        return json_encode([
            'street' => $value['street'],
            'city' => $value['city'],
            'state' => $value['state'],
            'postal_code' => $value['postal_code']
        ]);
    }
}

Then, in your model you'll be able to use both in a situation like this:

class User extends Model
{
    protected $casts = [
        'address' => Address::class,
        'phone' => PhoneNumber::class
    ];
}

Custom casts provide a clean, reusable way to handle complex data transformations while keeping your models lean and maintainable.


The post Customizing Data Transformations with Laravel Casts appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow