Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 16, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 16, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 16, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 16, 2025

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025

      Minecraft licensing robbed us of this controversial NFL schedule release video

      May 16, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The power of generators

      May 16, 2025
      Recent

      The power of generators

      May 16, 2025

      Simplify Factory Associations with Laravel’s UseFactory Attribute

      May 16, 2025

      This Week in Laravel: React Native, PhpStorm Junie, and more

      May 16, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025
      Recent

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Customizing Data Transformations with Laravel Casts

    Customizing Data Transformations with Laravel Casts

    December 20, 2024

    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:

    <?php
    
    namespace AppCasts;
    
    use IlluminateContractsDatabaseEloquentCastsAttributes;
    use IlluminateDatabaseEloquentModel;
    
    class PhoneNumber implements CastsAttributes
    {
        public function get(Model $model, string $key, mixed $value, array $attributes): string
        {
            return sprintf(
                "+%d (%d) %d-%d",
                ...explode('|', $value)
            );
        }
    
        public function set(Model $model, string $key, mixed $value, array $attributes): string
        {
            $value = preg_replace('/[^0-9]/', '', $value);
            return implode('|', [
                substr($value, 0, 1),
                substr($value, 1, 3),
                substr($value, 4, 3),
                substr($value, 7)
            ]);
        }
    }
    

    And another example of using an address formatter:

    <?php
    
    namespace AppCasts;
    
    use IlluminateContractsDatabaseEloquentCastsAttributes;
    use IlluminateDatabaseEloquentModel;
    
    class Address implements CastsAttributes
    {
        public function get(Model $model, string $key, mixed $value, array $attributes): array
        {
            $data = json_decode($value, true);
            
            return [
                'street' => $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.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleSet Data on a Fluent Instance in Laravel 11.36
    Next Article Automated API documentation of Laravel API resources

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 16, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2022-4363 – Wholesale Market WooCommerce CSRF Vulnerability

    May 16, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Counters – keep track of anything

    Linux

    ORiGAMi: A Machine Learning Architecture for the Document Model

    Databases

    A Few Ways That Cloudways Makes Running This Site a Little Easier

    News & Updates

    Microsoft Edge will also block uBlock Origin, but it may not be just yet (Update)

    News & Updates
    Hostinger

    Highlights

    Web Development

    Hire AI Developer: Cost Breakdown, Skills & Best Platforms for 2025

    February 17, 2025

    Artificial intelligence (AI) is reshaping industries, driving automation, and optimizing business processes worldwide. According to…

    OpenAI and Deepmind insiders demand a right to warn, OpenAI Offers a peek Inside the guts of ChatGPT, a new SORA rival, and more!

    June 10, 2024

    InfoCert hackerata: in vendita 5,5 milioni di dati rubati

    December 30, 2024

    The Future of DeFi: Key Trends Driving the Next Wave of Financial Innovation

    March 26, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.